gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:04:43 24 4
gpt4 key购买 nike

每当我在 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也有效。让我向您展示如何实现 map 。首先,你创建了这个东西:

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

要向 map 添加内容,您需要一个键,它是一个字符串。您可以使用计数器或其他东西来知道该数字并将该数字附加到“t”或“thread”之类的东西。然后您可以将键(字符串)和值(线程)添加到 HashMap 中。

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.

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

关于java - 在 java swing 中单击按钮时创建具有新名称的类的新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32687670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com