本文主要是介绍18 CyclicBarrier CountDownLacth,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
CyclicBarrier使用
假设只有一个场景,每个线程代表一个跑步运动员,当运动员都准备好后,才一起出发,只要有一个人没有准备好,大家都等待。
代码示例:
import java.io.IOException; import java.util.Random; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class UseCyclicBarrier {
static class Runner implements Runnable { private CyclicBarrier barrier; private String name;
public Runner(CyclicBarrier barrier, String name) { this.barrier = barrier; this.name = name; } @Override public void run() { try { Thread.sleep(1000 * (new Random()).nextInt(5)); System.out.println(name + "OK."); barrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } System.out.println(name + " Go!!"); } } public static void main(String[] args) throws IOException, InterruptedException { /** * 当达到3个await后,一起执行等待后面的代码 */ CyclicBarrier barrier = new CyclicBarrier(3); // 3
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(new Thread(new Runner(barrier, "zhangsan"))); executor.submit(new Thread(new Runner(barrier, "lisi"))); executor.submit(new Thread(new Runner(barrier, "wangwu")));
executor.shutdown(); }
} |
代码结果: lisiOK. wangwuOK. zhangsanOK. zhangsan Go!! wangwu Go!! lisi Go!! |
CountDownLacth使用
它经常用于监听某些初始化操作,等待初始化执行完毕后,通知主线程继续工作。
代码示例:
import java.util.concurrent.CountDownLatch;
/** * new CountDownLatch(2)中的参数是2,即当countDown.await()后 * 需要2次countDown.countDown();后才会去执行countDown.await()后面的代码 * @author Vision_TXG * */ public class UseCountDownLatch {
public static void main(String[] args) { //注意参数 final CountDownLatch countDown = new CountDownLatch(2); Thread t1 = new Thread(new Runnable() { @Override public void run() { try { System.out.println("进入线程t1" + "等待其他线程处理完成。。。"); countDown.await();//需要等待两个countDown.countDown()操作,由定义的参数决定 System.out.println("t1线程继续执行...."); } catch (InterruptedException e) { e.printStackTrace(); } } },"t1"); Thread t2 = new Thread(new Runnable() { @Override public void run() { try { System.out.println("t2线程进行初始化操作..."); Thread.sleep(3000); System.out.println("t2线程初始化完毕,通知t1线程继续..."); countDown.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread t3 = new Thread(new Runnable() { @Override public void run() { try { System.out.println("t3线程进行初始化操作..."); Thread.sleep(4000); System.out.println("t3线程初始化完毕,通知t1线程继续..."); countDown.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }); t1.start(); t2.start(); t3.start(); } }
|
代码执行结果: 进入线程t1等待其他线程处理完成。。。 t2线程进行初始化操作... t3线程进行初始化操作... t2线程初始化完毕,通知t1线程继续... t3线程初始化完毕,通知t1线程继续... t1线程继续执行.... |
注意:CyclicBarrier和CountDownLacth的区别
CountDownLacth是一个线程等待,其他的n个线程发出通知。针对的是一个线程
CyclicBarrier的线程都是参与阻塞的。针对的是多个线程。
这篇关于18 CyclicBarrier CountDownLacth的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!