java 主线程调用子线程后 可以用join的方式等待子线程返回, 再继续。
也可以用CompletionService 的take().get() 方法得到返回结果后再继续。
如果不需要等待子线程的结果的话,main线程可以直接结束, 子线程还会继续运行。
如果需要设置当main线程结束时, 子线程也停止。 可以将子线程设置成守护线程daemon。
也可以用CompletionService 的take().get() 方法得到返回结果后再继续。
ExecutorService es = Executors.newFixedThreadPool(10);
CompletionService<List<StatisticErrorBean>> cs = new ExecutorCompletionService<List<StatisticErrorBean>>(
es);
for (int i = 0; i < urlFolderList.size(); i++) {
cs.submit(new ConsumerErrorTask(urlFolderList.get(i).getUrl(), urlFolderList.get(i).getFolder(), reportMinus1, reportAdd1, reportS, this));
}
for (int i = 0; i < urlFolderList.size(); i++) {
List<StatisticErrorBean> list = cs.take().get();
if(list == null){
logger.debug("list is null");
continue;
}
combineList(resultList, list);
}
es.shutdown();
如果不需要等待子线程的结果的话,main线程可以直接结束, 子线程还会继续运行。
如果需要设置当main线程结束时, 子线程也停止。 可以将子线程设置成守护线程daemon。
public class Test extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("test");
}
}
public static void main(String[] args) throws InterruptedException {
Test test=new Test();
//test.setDaemon(true);//Of course.if set daemon thread. the child thread will exit
test.start();
Thread.sleep(3000);
System.out.println("return");
return;
}
}