1 package com.thread.test.thread; 2 3 import java.util.Random; 4 import java.util.concurrent.*; 5 6 /** 7 * CyclicBarrier 8 * 同步工具:允许一组线 ...
1 package com.thread.test.thread; 2 3 import java.util.Random; 4 import java.util.concurrent.*; 5 6 /** 7 * CyclicBarrier 8 * 同步工具:允许一组线程共同等待一个壁垒点 9 * 适用于固定数量线程的同步10 * 等待线程释放后可以重复使用11 * 12 * Created by windwant on 2016/5/27.13 */14 public class MyCyclicBarrier {15 public static void main(String[] args) {16 ExecutorService es = Executors.newCachedThreadPool();17 CyclicBarrier cb = new CyclicBarrier(5, new MainTask());//MainTask可选18 Random r = new Random();19 es.execute(new SubTask(cb, r.nextInt(10), "task1"));20 es.execute(new SubTask(cb, r.nextInt(10), "task2"));21 es.execute(new SubTask(cb, r.nextInt(10), "task3"));22 es.execute(new SubTask(cb, r.nextInt(10), "task4"));23 es.execute(new SubTask(cb, r.nextInt(10), "task5"));24 es.shutdown();25 }26 }27 28 class MainTask implements Runnable {29 30 public void run() {31 try {32 System.out.println("mian task begin");33 for (int i = 0; i < 5; i++) {34 Thread.sleep(1000);35 System.out.println("============" + i + "============");36 }37 System.out.println("mian task implemented");38 } catch (Exception e) {39 e.printStackTrace();40 }41 42 }43 }44 45 class SubTask implements Runnable{46 47 private CyclicBarrier cb;48 49 private int seconds;50 51 private String taskName;52 53 SubTask(CyclicBarrier cb, int seconds, String taskName){54 this.cb = cb;55 this.seconds = seconds;56 this.taskName = taskName;57 }58 59 public void run() {60 try{61 System.out.println("subtask " + taskName + " begin, need time: " + seconds + "s");62 long b = System.currentTimeMillis();63 for (int i = 0; i < seconds; i++) {64 Thread.sleep(1000);65 System.out.println("subtask: " + taskName + "============" + i + "============");66 }67 long d = System.currentTimeMillis() - b;68 System.out.println("subtask " + taskName + " over, executing time: " + TimeUnit.SECONDS.convert(d, TimeUnit.MILLISECONDS));69 cb.await();70 } catch (InterruptedException e) {71 e.printStackTrace();72 } catch (BrokenBarrierException e) {73 e.printStackTrace();74 }75 }76 }
原标题:CyclicBarrier 可重用同步工具
关键词:ie
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。