multithreading - Creating a new object of a class with a new name on clicking a button in java swing -
i want start new thread new object name, of specific class whenever click button in java swing application. example
thread t1 = new myclass(); t1.start(); thread t2 = new myclass(); t2.start(); thread t3 = new myclass(); t3.start(); ... so on...
how can achieve this?
i think should use arraylist<e> this. first lets create one:
arraylist<thread> threads = new arraylist<> (); now have empty arraylist of threads. when want add new thread, use add method.
thread t = new myclass(); threads.add(t); //use array list declared above ^^^^ t.start(); and if want thread, use get method. example,
thread thefirstthread = threads.get(0); you should declare array list in class, not in method new array list not created every time call method.
i know want create thread different name. might possible reflection (or not) think arraylist more suitable.
edit:
as madprogrammer has suggested, hashmap works well. let me show how implement map. first, create thing:
hashmap<string, thread> threadsmap = new hashmap<> (); to add stuff map need key, string. can use counter or know number , append number "t" or "thread". , can add key (the string) , value (the thread) hash map.
threadsmap.put (key, new myclass()); //key string mentioned. and thread corresponding key. in example, first thread:
threadsmap.get("thread1"); //the string string pass in when add first thread. now adventage of method not limited numbers key threads. can use valid string. can increase readability.
Comments
Post a Comment