Java uses thread. Join to divide a single task into multiple tasks and merge the result sets.

Source: Internet
Author: User

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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.