了解ComletableFuture的使用。设想了一个使用场景: 现在一个任务需要多线程执行三个子任务,当三个子任务中如果有一个任务执行出现问题返回false,则其他子任务应当立刻停止。
public class MyTest {
public static final ExecutorService threadPool =
new ThreadPoolExecutor(20,50,
60L, TimeUnit.SECONDS,new ArrayBlockingQueue<>(50),
new ThreadPoolExecutor.AbortPolicy());
public static void main(String[] args) {
new MyTest().doTestA();
}
public void doTestA(){
CompletableFuture<Void> f1 = CompletableFuture.supplyAsync(() ->{
System.out.println(Thread.currentThread().getName() + "f1");
compute(1000000);
return false;
},threadPool).thenAccept((result) -> {
if(!result){
System.out.println(Thread.currentThread().getName() + "由于f1失败,提前退出");
threadPool.shutdownNow();
return;
}
});
CompletableFuture<Void> f2 = CompletableFuture.supplyAsync(() ->{
System.out.println(Thread.currentThread().getName() + "f2");
compute(1000000000);
return true;
},threadPool).thenAccept((result) -> {
if(!result){
System.out.println(Thread.currentThread().getName() + "由于f2失败,提前退出");
}
});
CompletableFuture<Void> f3 = CompletableFuture.supplyAsync(() ->{
System.out.println(Thread.currentThread().getName() + "f3");
compute(1000000000);
return true;
},threadPool).thenAccept((result) -> {
if(!result){
System.out.println(Thread.currentThread().getName() + "由于f3失败,提前退出");
}
});
System.out.println(Thread.currentThread().getName() + "主线程");
}
public void doTest(){
ExecutorService pool = Executors.newCachedThreadPool();
pool.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println( Thread.currentThread().getName() + " 1 ");
}
});
pool.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println( Thread.currentThread().getName() + " 2 ");
}
});
System.out.println("主线程");
}
public void compute(long num){
List<Integer> list = new ArrayList<>();
for(int i=0;i<num;i++){
if(!Thread.currentThread().isInterrupted())
break;
list.add(new Integer(new Random().nextInt(100000000)));
}
Stream<Integer> sorted = list.parallelStream().sorted();
sorted.collect(Collectors.toList());
}
}
这段 Demo 的关键就在于
|