代码正在进入死锁。即使它在命中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 :::::: ");
}
}
}
}发布于 2017-02-16 06:41:08
当你这样做的时候
synchronized(this)你锁定了整个类。它将被锁定,直到该代码块的末尾。由于您将标志声明为volatile,因此不需要显式同步。
在这种情况下,您根本不需要向wait()和notify发送信号。但是,如果您希望拥有一些原子业务逻辑,则需要重新编写代码,以避免将类作为键阻塞整个大块。
发布于 2017-02-18 01:23:45
您的程序不会进入死锁-无论是在运行时,还是在调试时。我想您不熟悉调试多个线程,对吧?也许在您看来,您的生产线程处于死锁状态,而您必须切换到消耗线程并继续调试?
https://stackoverflow.com/questions/42261398
复制相似问题