Reputation: 182
I want to start a new thread with a new object name, of a specific class whenever I click a button in java Swing application. For example
Thread t1 = new MyClass();
t1.start();
Thread t2 = new MyClass();
t2.start();
Thread t3 = new MyClass();
t3.start();
...
so on...
How can I achieve this?
Upvotes: 1
Views: 233
Reputation: 270890
I think you should use a ArrayList<E>
for this. First lets create one:
ArrayList<Thread> threads = new ArrayList<> ();
Now you have an empty ArrayList
of threads. When you want to add a new thread, use the add
method.
Thread t = new MyClass();
threads.add(t); //Use the array list declared above ^^^^
t.start();
And if you want to get the thread, use the get
method. For example,
Thread theFirstThread = threads.get(0);
You probably should declare the array list in the class, not in the method so that a new array list would not be created every time you call the method.
I know you actually want to create a thread with a different name. It might be possible with reflection (or not) but I think an ArrayList
is more suitable.
EDIT:
As MadProgrammer has suggested, a HashMap
works as well. Let me show you how to implement a map. First, you create the thing:
HashMap<String, Thread> threadsMap = new HashMap<> ();
To add stuff to the map you need a key, which is a string. You can use a counter or something to know the number and append the number to something like "t" or "thread". And then you can add the key (the string) and the value (the thread) to the hash map.
threadsMap.put (key, new MyClass()); //key is the string that I mentioned.
And you get the thread by its corresponding key. In this example, I get the first thread:
threadsMap.get("thread1"); //the string is the string you pass in when you add the first thread.
Now the adventage of this method is that you are not limited to numbers as key to get the threads. You can use any valid string. This can increase readability.
Upvotes: 4