代碼進入死鎖。即使它一出現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()',會發生什麼?你在想什麼會喚醒他們其中一個呢? –