CyclicBarrier的用法
并行任务的写法
执行结果
张三到达了集合点
李四到达了集合点
王五到达了集合点
------给你们发门票--------
王五开始玩喽
李四开始玩喽
张三开始玩喽
具体的代码
CyclicBarrierTest
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CyclicBarrierTest {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() {
@Override
public void run() {
System.out.println("------"+"给你们发门票"+"--------");
}
});
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
executorService.submit(new Thread(new TravelTask(cyclicBarrier,"张三")));
executorService.submit(new Thread(new TravelTask(cyclicBarrier,"李四")));
executorService.submit(new Thread(new TravelTask(cyclicBarrier,"王五")));
executorService.shutdown();
}
}
TravelTask
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class TravelTask implements Runnable {
private CyclicBarrier cyclicBarrier;
private String name;
public TravelTask(CyclicBarrier cyclicBarrier, String name) {
this.cyclicBarrier = cyclicBarrier;
this.name = name;
}
@Override
public void run() {
System.out.println(this.name+"到达了集合点");
try {
cyclicBarrier.await();
System.out.println(this.name+"开始玩喽");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
不好的写法
场景1 await使用不好会阻塞,其它线程走不了
1.当线程池的核心线程数为2
2.往线程池里放了20个线程
3.run方法正常顺利执行最后一行 await()了
此时只能执行两个线程 其它线程执行不了