線程併發工具--CyclicBarrier

CyclicBarrier能實現的效果是多個線程同時執行,這些線程執行的時間不一。但是要求在某一個點上,需要這些線程都執行完畢了之後,全部線程才能往下執行。

下面是示例程序:

ExecutorService service = Executors.newCachedThreadPool();
		final CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
		for(int i = 0;i<3;i++){
			Runnable runnable = new Runnable(){
				
				Random random = new Random();
				
				@Override
				public void run() {
					try {
						Thread.sleep(random.nextInt(5000));
						System.out.println("point 1:"+Thread.currentThread().getName()+" execute complate.");
						cyclicBarrier.await();
					} catch (InterruptedException | BrokenBarrierException e) {
						e.printStackTrace();
					}
					
					try {
						Thread.sleep(random.nextInt(5000));
						System.out.println("point 2:"+Thread.currentThread().getName()+" execute complate.");
						cyclicBarrier.await();
					} catch (InterruptedException | BrokenBarrierException e) {
						e.printStackTrace();
					}
					
					try {
						Thread.sleep(random.nextInt(5000));
						System.out.println("point 3:"+Thread.currentThread().getName()+" execute complate.");
						cyclicBarrier.await();
					} catch (InterruptedException | BrokenBarrierException e) {
						e.printStackTrace();
					}
					
					try {
						Thread.sleep(random.nextInt(5000));
						System.out.println("point 4:"+Thread.currentThread().getName()+" execute complate.");
						cyclicBarrier.await();
					} catch (InterruptedException | BrokenBarrierException e) {
						e.printStackTrace();
					}
				}
			};
			service.execute(runnable);
			//service.shutdown();
		}
執行結果:
point 1:pool-1-thread-3 execute complate.
point 1:pool-1-thread-2 execute complate.
point 1:pool-1-thread-1 execute complate.
point 2:pool-1-thread-2 execute complate.
point 2:pool-1-thread-1 execute complate.
point 2:pool-1-thread-3 execute complate.
point 3:pool-1-thread-3 execute complate.
point 3:pool-1-thread-1 execute complate.
point 3:pool-1-thread-2 execute complate.
point 4:pool-1-thread-1 execute complate.
point 4:pool-1-thread-2 execute complate.
point 4:pool-1-thread-3 execute complate.
可以看到,到達麼一個點的順序可能不固定,但是沒有說一個線程纔到達point1的時候,另外一個線程已經達到point2了,即大家共同達到一個點之後纔會繼續往下執行。


發佈了61 篇原創文章 · 獲贊 9 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章