7 Java多线程:JUC(上)( 二 )

CyclicBarrier执行后的效果是:

7 Java多线程:JUC(上)

文章插图
四、Exchanger
Exchanger的功能如果用图来表示的话,就会是这样的:
【7 Java多线程:JUC(上)】
7 Java多线程:JUC(上)

文章插图
Exchanger实例代码:
/** * 交换机 * * @author 湘王 */public class ExchangerTester implements Runnable {Exchanger<Object> exchanger = null;Object object = null;public ExchangerTester(Exchanger<Object> exchanger, Object object) {this.exchanger = exchanger;this.object = object;}@Overridepublic void run() {try {Object previous = this.object;this.object = this.exchanger.exchange(this.object);System.out.println(Thread.currentThread().getName() + " 用对象 " + previous + " 换对象 " + this.object);} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args) {Exchanger<Object> exchanger = new Exchanger<Object>();ExchangerTester tester1 = new ExchangerTester(exchanger, "A");ExchangerTester tester2 = new ExchangerTester(exchanger, "B");new Thread(tester1).start();new Thread(tester2).start();}}Exchanger执行后的效果是:
7 Java多线程:JUC(上)

文章插图
把这四种同步器掌握好(包括它们的组合使用),几乎可以解决90%以上的使用多线程的场景问题,再也不用担心不会多线程了 。
感谢您的大驾光临!咨询技术、产品、运营和管理相关问题,请关注后留言 。欢迎骚扰,不胜荣幸~

推荐阅读