|
| 1 | +package edu.maskleo.module1; |
| 2 | + |
| 3 | +import java.util.concurrent.BrokenBarrierException; |
| 4 | +import java.util.concurrent.CyclicBarrier; |
| 5 | +import java.util.concurrent.TimeUnit; |
| 6 | +import java.util.concurrent.TimeoutException; |
| 7 | + |
| 8 | +public class CyclicBarrierTest3 { |
| 9 | + |
| 10 | + public static void main(String[] args) { |
| 11 | + int N = 4; |
| 12 | + CyclicBarrier barrier = new CyclicBarrier(N); |
| 13 | + |
| 14 | + for (int i = 0; i < N; i++) { |
| 15 | + if (i < N - 1) |
| 16 | + new Thread(new Writer(barrier), "t" + i).start(); |
| 17 | + else { |
| 18 | + try { |
| 19 | + Thread.sleep(5000); |
| 20 | + } catch (InterruptedException e) { |
| 21 | + e.printStackTrace(); |
| 22 | + } |
| 23 | + new Thread(new Writer(barrier), "t" + i).start(); |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + static class Writer implements Runnable { |
| 29 | + private CyclicBarrier cyclicBarrier; |
| 30 | + |
| 31 | + public Writer(CyclicBarrier cyclicBarrier) { |
| 32 | + this.cyclicBarrier = cyclicBarrier; |
| 33 | + } |
| 34 | + |
| 35 | + @Override |
| 36 | + public void run() { |
| 37 | + System.out.println("线程" + Thread.currentThread().getName() + " 正在写入数据..."); |
| 38 | + try { |
| 39 | + Thread.sleep(5000); //以睡眠来模拟写入数据操作 |
| 40 | + System.out.println("线程" + Thread.currentThread().getName() + " 写入数据完毕,等待其他线程写入完毕"); |
| 41 | + try { |
| 42 | + cyclicBarrier.await(2000, TimeUnit.MILLISECONDS); |
| 43 | + } catch (TimeoutException e) { |
| 44 | + System.out.println(Thread.currentThread().getName() + " 1111"); |
| 45 | + } |
| 46 | + } catch (InterruptedException e) { |
| 47 | + System.out.println(Thread.currentThread().getName() + " 2222"); |
| 48 | + } catch (BrokenBarrierException e) { |
| 49 | + System.out.println(Thread.currentThread().getName() + " 3333"); |
| 50 | + } |
| 51 | + System.out.println(Thread.currentThread().getName() + " 所有线程写入完毕,继续处理其他任务..."); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | +} |
0 commit comments