多线程(八、同步计数器-CyclicBarrier)
CyclicBarrier-循环栅栏
线程到达栅栏时调用await方法被阻塞,只有线程数据达到栅栏设置的阈值时,栅栏放行,所有线程继续执行,此轮结束,栅栏进入下一轮。
案例:3个线程等待栅栏放行
Task
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class Task implements Runnable{
private CyclicBarrier cyclicBarrier;
public Task(CyclicBarrier cyclicBarrier) {
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + "准备就绪");
cyclicBarrier.await();
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + "中断了......");
} catch (BrokenBarrierException e) {
System.out.println(Thread.currentThread().getName() + "抛出损坏异常....");
}
}
}
启动文件
import java.util.concurrent.CyclicBarrier;
public class Main {
public static void main(String[] args) throws InterruptedException {
System.out.println("主线程开始......");
CyclicBarrier cb = new CyclicBarrier(3, new Runnable(){
@Override
public void run() {
System.out.println("子线程全部就位,开始执行制定任务......");
}
});
Thread t1 = new Thread(new Task(cb), "Thread-1");
Thread t2 = new Thread(new Task(cb), "Thread-2");
Thread t3 = new Thread(new Task(cb), "Thread-3");
t1.start();
t2.start();
t3.start();
Thread.sleep(2000);
System.out.println("主线程执行完毕");
}
}
结果:
成都创新互联主营玉溪网站建设的网络公司,主营网站建设方案,重庆APP开发公司,玉溪h5微信平台小程序开发搭建,玉溪网站营销推广欢迎玉溪等地区企业咨询
CyclicBarrier的异常
CyclicBarrier如果不能满足阈值,超时或者等待的线程被中断了,则所有等待线程都会抛出损坏异常,然后进入下一轮。
案例:损坏异常,假设阈值为4,已经有3个线程等待,其中一个中断。
Task代码不变
启动文件修改
import java.util.concurrent.CyclicBarrier;
public class Main {
public static void main(String[] args) throws InterruptedException {
System.out.println("主线程开始......");
CyclicBarrier cb = new CyclicBarrier(4, new Runnable(){
@Override
public void run() {
System.out.println("子线程全部就位,开始执行制定任务......");
}
});
Thread t1 = new Thread(new Task(cb), "Thread-1");
Thread t2 = new Thread(new Task(cb), "Thread-2");
Thread t3 = new Thread(new Task(cb), "Thread-3");
t1.start();
t2.start();
t3.start();
Thread.sleep(1000);
t1.interrupt();
Thread.sleep(2000);
System.out.println("主线程执行完毕");
}
}
结果:
源码分析:
CyclicBarrier基于ReentrantLock和Condition实现锁机制。
成员变量
await方法:
breakBarrier损坏方法:
当前名称:多线程(八、同步计数器-CyclicBarrier)
文章转载:http://scyanting.com/article/ghhgcp.html