每次手动wait 才会进入另一个线程....notify 没效果

来源:7-6 用wait/notify实现

qq_改成什么名字呢_0

2019-10-18

之前用notify 没效果 替换成 notifyAll 一样,都是yiyang

图片描述图片描述

package com.company;

import java.util.ArrayList;

public class Test {
private static final ArrayList listDobule = new ArrayList(10);
public static void main(String[] args) throws InterruptedException {
new AddThe().start();
Thread.sleep(10);
new RemoveThe().start();
}

static class AddThe extends  Thread{
    @Override
    public void run() {
        synchronized (listDobule) {
            while (true) {
                if (listDobule.size() == 10) {
                    try {
                        listDobule.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
                listDobule.add(Math.random());
                System.out.println(listDobule.size()+" 添加资源:" + Math.random());
                listDobule.notify();
            }
        }
    }
}


static class RemoveThe extends  Thread{
    @Override
    public void run() {
        synchronized (listDobule){
            while (true) {
                if (listDobule.size() == 0) {
                    try {
                        listDobule.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("消费资源:" + listDobule.get(0));
                listDobule.remove(listDobule.get(0));
                listDobule.notify();
            }
        }
    }
}

}

写回答

1回答

悟空

2019-10-18

你把synchronized的锁对象换一个独立的new Object()后再试一下。

另外,麻烦把代码用文字形式贴一下,我复制到我的电脑运行试一下。

0
3
悟空
回复
qq_改成什么名字呢_0
恩好的
2019-10-18
共3条回复

线程八大核心+Java并发原理及企业级并发解决方案

完整的并发知识网络+丰富的工作内容分享+50余道并发高频面试题

2512 学习 · 939 问题

查看课程