执行任务的具体线程类:
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;
}
@Override
public 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;
}
}
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 {
//主线程等待时间不超过10秒,若超过,则主线程直接走
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();//中断超时的线程
}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]