package test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ChildThreadTest{
public static void main(String[] args){
ExecutorService executorService = Executors.newCachedThreadPool();
Future<Boolean> future = executorService.submit(new Callable<Boolean>() {
// 子線程1
@Override
public Boolean call() throws Exception {
// 子線程1
Future<Boolean> future1 = executorService.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Thread.sleep(1000);
System.out.println("子線程1執行了...");
return true;
}
});
// 子線程2
Future<Boolean> future2 = executorService.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
System.out.println("子線程2執行了...");
return true;
}
});
// 子線程3
Future<Boolean> future3 = executorService.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
System.out.println("子線程3執行了...");
return true;
}
});
future1.get();
future2.get();
future3.get();
return true;
}
});
try {
// 阻塞
future.get();
System.out.println("外部線程執行了....");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 啓動有序關閉,在此過程中執行先前提交的任務,但不接受任何新任務。如果已經關閉,調用不會產生額外的效果。
System.out.println("線程關閉!");
executorService.shutdown();
}
}
}
執行結果: