每次手动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()后再试一下。
另外,麻烦把代码用文字形式贴一下,我复制到我的电脑运行试一下。
032019-10-18
相似问题