线程系列:wait()与notifyAll()的简单实例

  • 首先wait()和notify()并不是Thread类中的函数,而是Object类中的。但是面试中,问到线程时,经常问到wait(),notify()机制。
    在这里插入图片描述
  • 下面是一个wait()和notifyAll()的实例。
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class WaitNotifyTest{

    private List synchedList;

    public WaitNotifyTest() {
        // 创建一个同步列表
        synchedList = Collections.synchronizedList(new LinkedList());
    }

    // 删除列表中的元素
    public void sendProduct() throws InterruptedException {
        synchronized (synchedList) {

            // 列表为空就等待
            while (synchedList.isEmpty()) {
                System.out.println(printTitle() + ":没有可搬运的产品,开始等待!");
                synchedList.wait();
            }
            String element = (String) synchedList.remove(0);
            System.out.println(printTitle() + ":开始搬运" + element + "!");
        }
    }

    // 添加元素到列表
    public void createProduct(String element) {
        synchronized (synchedList) {

            // 添加一个元素,并通知元素已存在
            synchedList.add(element);
            System.out.println(printTitle() + ":产品:'" + element + "'生产完成,发出提醒");
            synchedList.notifyAll();
        }

    }

    public static void main(String[] args) {
        final WaitNotifyTest demo = new WaitNotifyTest();

        Runnable runRemove = new Runnable() {

            public void run() {
                try {
                    demo.sendProduct();
                } catch (Exception x) {
                    System.out.println("Exception thrown.");
                }
            }
        };

        Runnable runAdd = new Runnable() {

            // 执行添加元素操作,并开始循环
            public void run() {
                System.out.println(printTitle() + ":开始生产...");
                try {
                    Thread.sleep(2000); //模拟生产产品所消耗的时间
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(printTitle() + ":" + e.getMessage());
                }

                demo.createProduct("ProjectA");
            }
        };


        Thread t1 = new Thread(runRemove, "运输员");
        t1.start();


        Thread t2 = new Thread(runAdd, "生产员");
        t2.start();


    }

    public static String getTime(long currentTime) {
        return new SimpleDateFormat("HH:mm:ss").format(currentTime);
    }

    public static String printTitle() {
        return getTime(System.currentTimeMillis()) + " " + Thread.currentThread().getName();
    }
}

运行输出结果如下
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值