zoukankan      html  css  js  c++  java
  • 线程间交换信息的方式--notify()方法和wait()方法

    2.Object类的notify和wait方法

    package edu.hubu.threadexchange;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * created by Sugar  2019/10/11 23:48
     */
    public class ObjectDemo {
        public static void main(String[] args) {
            // 定义一个锁对象
            Object lock = new Object();
            List<String> list = new ArrayList<>();
            // 实现线程A
            Thread threadA = new Thread(() -> {
                synchronized (lock) {
                    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)
                            lock.notify();// 唤醒B线程
                    }
                }
            });
            // 实现线程B
            Thread threadB = new Thread(() -> {
                while (true) {
                    synchronized (lock) {
                        if (list.size() != 5) {
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        System.out.println("线程B收到通知,开始执行自己的业务...");
                    }
                }
            });
            // 需要先启动线程B
            threadB.start();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 再启动线程A
            threadA.start();
        }
    
    }
  • 相关阅读:
    UIViewController生命周期
    NSTImer重复执行任务
    IOS平台汉字转拼音方案
    @properties指针说明
    自定义yum仓库
    man手册、zip备份
    ln 软连接与硬连接
    fdisk分区规划和添加wap交换空间
    window部署ftp服务器
    配置附加权限和LDAP
  • 原文地址:https://www.cnblogs.com/HubuSugar/p/11813101.html
Copyright © 2011-2022 走看看