package com.swiftpass.spi.thread;
import java.util.Random;
import java.util.concurrent.Callable;
public class TestThread implements Callable<Boolean> {
public Boolean call() throws Exception {
int i = new Random().nextInt(4);
if(i%2==1){
System.out.println(Thread.currentThread().getName()+"执行异常");
throw new RuntimeException("111111");
}
System.out.println(Thread.currentThread().getName()+"执行成功");
return true;
}
}
@Test
public void test() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(100);
List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>();
for (int i = 1; i < 100; i++) {
TestThread testThread = new TestThread();
Future<Boolean> future = executorService.submit(testThread);
futures.add(future);
}
for(Future<Boolean> future :futures){
try{
Boolean aBoolean = future.get();
}catch (Exception e){
}
}
System.out.println("回归主流程");
Thread.sleep(1000000);
}
这样写会等所有线程结束后回归主流程
@Test
public void test1() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(100);
List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>();
for (int i = 1; i < 100; i++) {
TestThread testThread = new TestThread();
Future<Boolean> future = executorService.submit(testThread);
futures.add(future);
}
try {
for (Future<Boolean> future : futures) {
Boolean aBoolean = future.get();
}
} catch (Exception e) {
}
System.out.println("回归主流程");
Thread.sleep(1000000);
}
这样实现,只要一个抛出异常,就直接返回主流程了,然后子线程会继续跑,不会结束。