在java swing中单击一个按钮时创建一个具有新名称的类的新对象



每当我单击java Swing应用程序中的按钮时,我想用特定类的新对象名称启动一个新线程。例如

Thread t1 = new MyClass();
t1.start();
Thread t2 = new MyClass();
t2.start();
Thread t3 = new MyClass();
t3.start();
...

等等……

我怎样才能做到这一点?

我认为您应该使用ArrayList<E>。首先让我们创建一个:

ArrayList<Thread> threads = new ArrayList<> ();

现在你有一个空的ArrayList线程。当你想添加一个新线程时,使用add方法。

Thread t = new MyClass();
threads.add(t); //Use the array list declared above ^^^^
t.start();

如果您想获得线程,请使用get方法。例如,

Thread theFirstThread = threads.get(0);

你可能应该在类中声明数组列表,而不是在方法中,这样就不会在每次调用方法时都创建一个新的数组列表。

我知道你实际上想用不同的名字创建一个线程。它可能是可能的反射(或不),但我认为ArrayList更合适。

编辑:

正如MadProgrammer所建议的,HashMap也可以工作。让我来演示一下如何实现一个地图。首先,创建如下内容:

HashMap<String, Thread> threadsMap = new HashMap<> ();

要向映射中添加内容,需要一个键,它是一个字符串。你可以使用计数器或其他东西来知道数字,并将数字附加到"t"或"线程"之类的东西上。然后你可以将键(字符串)和值(线程)添加到哈希映射中。

threadsMap.put (key, new MyClass()); //key is the string that I mentioned.

通过对应的键得到线程。在这个例子中,我得到了第一个线程:

threadsMap.get("thread1"); //the string is the string you pass in when you add the first thread.

现在这个方法的优点是,您不局限于以数字作为键来获取线程。您可以使用任何有效的字符串。这可以提高可读性。

相关内容

最新更新