程序没错,,,不过我感觉synchronized不能加,加也没用,,,,他们各自操作各自的run方法,我感觉这样写比较好- package aaaa;
- import java.util.Random;
- import java.util.concurrent.CyclicBarrier;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- public class CyclicBarrierTest {
- public static void main(String[] args) {
- ExecutorService service = Executors.newCachedThreadPool();
- final CyclicBarrier cb = new CyclicBarrier(5);
- for(int i = 0; i < 5; i++) {
- Runnable runnable = new Runnable() {
- @Override
- public void run() {
- try {
- Thread.sleep(new Random().nextInt(1000));
- //为什么cb.getNumberWaiting()方法得到等待的线程的数据不正确呢????
- System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合地点1,当前已有" + (cb.getNumberWaiting() ) + "已经到达," + (cb.getNumberWaiting() == 4 ? "都到齐了,继续走吧" : "正在等待"));
- cb.await();
-
- Thread.sleep(new Random().nextInt(1000));
- System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合地点2,当前已有" + (cb.getNumberWaiting() ) + "已经到达," + (cb.getNumberWaiting() == 4 ? "都到齐了,继续走吧" : "正在等待"));
- cb.await();
-
- Thread.sleep(new Random().nextInt(1000));
- System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合地点3,当前已有" + (cb.getNumberWaiting() ) + "已经到达," + (cb.getNumberWaiting() == 4 ? "都到齐了,继续走吧" : "正在等待"));
- cb.await();
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- };
- service.execute(runnable);
- }
- service.shutdown();
- }
- }
复制代码
屡试不爽
|
-
a.png
(10.2 KB, 下载次数: 10)
|