• Java-CyclicBarrier的简单样例


    内容:一个主任务等待两个子任务,通过CyclicBarrier的await()实现。此Runnable任务在CyclicBarrier的数目达到后,全部其他线程被唤醒前被运行。

    public class CyclicBarrierTest {
    	
    	class MainTask implements Runnable {
    		@Override
    		public void run() {
    			System.out.println(">>>>主任务開始运行!<<<<");
    		}
    	}
    	
    	class SubTask implements Runnable {
    		private String name;
    		private CyclicBarrier cyclicBarrier;
    		
    		SubTask(String name, CyclicBarrier cyclicBarrier) {
    			this.name = name;
    			this.cyclicBarrier = cyclicBarrier;
    		}
    		
    		@Override
    		public void run() {
    			System.out.println("[子任务" + name + "]開始运行了!");
    			for (int i = 0; i < 999999; i++) ;
    			System.out.println("[子任务" + name + "]运行完毕了,并通知障碍器已经完毕了");
    			
    			try {
    				cyclicBarrier.await();
    			} catch (InterruptedException  e) {
    				e.printStackTrace();
    			} catch (BrokenBarrierException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    	
    	public static void main(String[] args) {
    		CyclicBarrierTest test = new CyclicBarrierTest();
    		CyclicBarrier cyclicBarrier = new CyclicBarrier(2, test.new MainTask());
    		SubTask A = test.new SubTask("A", cyclicBarrier);
    		SubTask B = test.new SubTask("B", cyclicBarrier);
    		ExecutorService executor = Executors.newCachedThreadPool();
    		executor.execute(A);
    		executor.execute(B);
    	}
    }



  • 相关阅读:
    BZOJ3156 防御准备
    BZOJ1911 [APIO2010] 特别行动队
    BZOJ1096 [ZJOI2007] 仓库建设
    HDU
    斜率优化的各种板子
    HDU
    HDU
    HDU
    HDU
    HDU
  • 原文地址:https://www.cnblogs.com/lxjshuju/p/7100441.html
Copyright © 2020-2023  润新知