代码进入死锁。即使它一出现wait()
即将生产者部分,它就陷入僵局。从我的理解,如果wait()
被击中,它应该去消费者线程,而不是进入死锁。我的生产者消费者代码进入死锁
package com.java.thread.self.practice;
public class Producer_Consumer {
private volatile boolean prodFlag = true;
private volatile boolean consFlag = false;
public static void main(String[] args){
Producer_Consumer producer_Consumer = new Producer_Consumer();
producer_Consumer.startThreads();
}
private void startThreads() {
Thread producer = new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
System.out.println("Before Producer invocation :::::: ");
producer();
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
Thread consumer = new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
System.out.println("Before Consumer invocation :::::: ");
consumer();
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
producer.start();
consumer.start();
}
void producer() throws InterruptedException {
System.out.println("Inside the producer method ::::: "+this.getClass());
synchronized(this){
if(prodFlag){
System.out.println("PRODUCE !!!");
consFlag = true;
System.out.println("Before calling wait in producer :::::: ");
notify();
wait();
System.out.println("After calling wait in producer :::::: ");
}else{
System.out.println("Before calling notify in producer :::::: ");
consFlag = true;
wait();
System.out.println("After calling notify in producer :::::: ");
}
}
}
void consumer() throws InterruptedException {
System.out.println("Inside the consumer method ::::: "+this.getClass());
synchronized(this){
if(consFlag){
System.out.println("CONSUME !!!");
prodFlag = true;
System.out.println("Before calling wait in consumer :::::: ");
notify();
wait();
System.out.println("After calling wait in consumer :::::: ");
}else{
System.out.println("Before calling notify in consumer :::::: ");
prodFlag = true;
wait();
System.out.println("After calling wait in consumer :::::: ");
}
}
}
}
我测试了你的代码,它没有死锁。他连续打印控制台中的“生产”“消费” – Flood2d
尝试调试模式。 –
如果生产者线程和消费者线程调用'notify()',然后他们都调用'wait()',会发生什么?你在想什么会唤醒他们其中一个呢? –