老师,想请问一下为什么我这里加了一个条件判断就会导致死锁
来源:7-6 用wait/notify实现

LambertJiang
2020-09-02
package redis.redis;
import java.util.LinkedList;
public class CustormAndProduct {
public static void main(String[] args) {
ListedQueueDemo queue = new ListedQueueDemo();
CustormAndProduct cs = new CustormAndProduct();
Produce pro = cs.new Produce(queue);
Cosumer cos = cs.new Cosumer(queue);
Thread th1 = new Thread(pro);
Thread th2 = new Thread(cos);
th1.start();
try {
Thread.sleep(20);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
th2.start();
try {
th1.join();
th2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行完成");
}
class Produce implements Runnable{
private ListedQueueDemo queue;
public Produce(ListedQueueDemo queue) {
this.queue = queue;
}
public void run() {
for (int i = 0; i < 200; i++) {
queue.push("当前插入的数据为"+i);
}
}
}
class Cosumer implements Runnable{
private ListedQueueDemo queue;
public Cosumer(ListedQueueDemo queue) {
this.queue = queue;
}
public void run() {
for (int i = 0; i < 200; i++) {
//这个位置
if(Math.random()>0.95) {
queue.take();
}
}
}
}
static class ListedQueueDemo{
private LinkedList<String> list = new LinkedList<String>();
public void push(String str) {
synchronized (list) {
if(list.size()>=10) {
try {
list.wait();
System.out.println("停止生产,队列满了!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.push(str);
System.out.println(str);
list.notify();
}
}
public synchronized String take() {
String reu = "";
synchronized (list) {
if(list.size()<=0) {
try {
list.wait();
System.out.println("停止消费,队列空了!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
reu = list.poll();
list.notify();
System.out.println("当前抽取数据为"+reu);
}
return reu;
}
}
}
写回答
1回答
-
这不是死锁,加了这个条件后,有概率queue.take();不执行,所以总的take数量就和push的不相等,所以就阻塞住了。
112020-09-02
相似问题