public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
Object obj = new Object();
//生产者
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
synchronized (obj) {
//如果有 等待
if (list.size() > 0) ;
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
//没有
list.add("aaa");
System.out.println(list);
//唤醒线程
obj.notify();
}
}
}
}).start();
//消费者
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
synchronized (obj) {
//弱国没有元素 等待
if (list.size() == 0) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果有元素
String s = list.remove(0);
System.out.println(list);
//唤醒生产过程
obj.notify();
}
}
}
}).start();
}
}
[JAVA] 线程 等待唤醒机制 生产者 和 消费者
最新推荐文章于 2024-07-14 22:26:46 发布