zoukankan      html  css  js  c++  java
  • 线程间交换信息的方式--JUC包中的并发工具

    5.借助Java并发包中的并发工具,比如CountDownLatch、同步屏障CyclicBarrier、信号量Semphore

    package edu.hubu.threadexchange;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.CountDownLatch;
    
    /**
     * created by Sugar  2019/10/11 23:50
     */
    public class JUCToolsDemo {
        public static void main(String[] args) {
            CountDownLatch countDownLatch = new CountDownLatch(1);
            List<String> list = new ArrayList<>();
            // 实现线程A
            Thread threadA = new Thread(() -> {
                for (int i = 1; i <= 10; i++) {
                    list.add("abc");
                    System.out.println("线程A向list中添加一个元素,此时list中的元素个数为:" + list.size());
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (list.size() == 5)
                        countDownLatch.countDown();
                }
            });
            // 实现线程B
            Thread threadB = new Thread(() -> {
                while (true) {
                    if (list.size() != 5) {
                        try {
                            countDownLatch.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("线程B收到通知,开始执行自己的业务...");
                    break;
                }
            });
            // 需要先启动线程B
            threadB.start();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 再启动线程A
            threadA.start();
        }
    
    }
  • 相关阅读:
    设计模式天天练。
    系统资料库msdb置疑或者不可用的解决方法
    依赖注入IOC
    重载、重写、隐藏的区别
    ASP.NET中的HttpWorkerRequest对像及其应用
    ASP.NET的错误处理机制
    Web.Config
    asp.net 2.0页面生命周期
    FileUpLoad控件上传大容量文件
    大文件上传
  • 原文地址:https://www.cnblogs.com/HubuSugar/p/11813218.html
Copyright © 2011-2022 走看看