Java中用Thread.join实现单任务分成多个任务最后合并结果集

执行任务的具体线程类:

package com.utils;

import java.util.ArrayList;
import java.util.List;

public class MyThread extends Thread {

	private List result = new ArrayList();
	
	private String selfName;
	
	public MyThread(String selfName) {
		super();
		this.selfName = selfName;
	}

	@Override
	public void run() {
		for(int i=0;i<3;i++){
			result.add(this.selfName + "-data" + i);
		}
	}
	
	public List getResult() {
		return result;
	}

	public void setResult(List result) {
		this.result = result;
	}

	public String getSelfName() {
		return selfName;
	}

	public void setSelfName(String selfName) {
		this.selfName = selfName;
	}

}


测试类:
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 resList = new ArrayList();
		List threads = new ArrayList();
		for(int i=0;i<3;i++){
			MyThread thread = new MyThread("Thread" + i);
			thread.start();
			threads.add(thread);
		}
		for (MyThread thread : threads) {
			try {
				//主线程等待时间不超过10秒,若超过,则主线程直接走
				thread.join(10000); 
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int i=0;i result = threads.get(i).getResult();
			if(result.size()==0 && threads.get(i).isAlive()){
				threads.get(i).interrupt();//中断超时的线程
			}else{
				resList.addAll(result);
			}
		}
		System.out.println("结果如下:\n" + resList);
	}

}

运行结果如下:

结果如下:
[Thread0-data0, Thread0-data1, Thread0-data2, Thread1-data0, Thread1-data1, Thread1-data2, Thread2-data0, Thread2-data1, Thread2-data2]

你可能感兴趣的:(JAVA基础)