The specific Thread class for executing the task:
Package COM. utils; import Java. util. arraylist; import Java. util. list; public class mythread extends thread {private list <string> result = new arraylist <string> (); Private string selfname; Public mythread (string selfname) {super (); this. selfname = selfname ;}@ overridepublic void run () {for (INT I = 0; I <3; I ++) {result. add (this. selfname + "-Data" + I) ;}} public list <string> getresult () {return result;} public void setresult (list <string> result) {This. result = result;} Public String getselfname () {return selfname;} public void setselfname (string selfname) {This. selfname = selfname ;}}
Test class:
Package COM. utils; import Java. util. arraylist; import Java. util. arrays; import Java. util. list; public class mythreadtest extends thread {public static void main (string [] ARGs) {list <string> reslist = new arraylist <string> (); list <mythread> threads = new arraylist <mythread> (); For (INT I = 0; I <3; I ++) {mythread thread = new mythread ("Thread" + I); thread. start (); threads. add (thread) ;}for (mythread thread: threads) {try {// the waiting time of the main thread cannot exceed 10 seconds. If the waiting time is exceeded, the main thread goes directly to the thread. join (10000);} catch (interruptedexception e) {e. printstacktrace () ;}}for (INT I = 0; I <threads. size (); I ++) {list <string> result = threads. get (I ). getresult (); If (result. size () = 0 & threads. get (I ). isalive () {threads. get (I ). interrupt (); // thread with interrupt timeout} else {reslist. addall (result) ;}} system. out. println ("Result: \ n" + reslist );}}
The running result is as follows:
The result is as follows:
[Thread0-data0, Thread0-data1, Thread0-data2, Thread1-data0, Thread1-data1, Thread1-data2, Thread2-data0, Thread2-data1]