Search code examples
javajava.util.concurrent

Java: wait() doesnt free lock. Why?


My code stops at "Producer started". Why wait() doesn't free lock? I use the same object in synchronized section, but it doesn't work.

class Processor {
    public void produce() throws InterruptedException {
        synchronized (this) {
            System.out.println("Producer started");
            wait();
            System.out.println("Producer ended");
        }
    }

    public void consume() throws InterruptedException {
        System.out.println("Consumer started");
        Scanner scanner = new Scanner(System.in);
        synchronized (this) {
            scanner.nextLine();
            System.out.println("go to producer");
            notify();
            Thread.sleep(1000);
            System.out.println("Consumer ended");
        }
    }
}

While I am running this code in different threads, I am using the same Processor object

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Processor processor = new Processor();

        Thread t1 = new Thread(() -> {
            try {
                processor.produce();
            } catch (InterruptedException e) {}
        });

        Thread t2 = new Thread(() -> {
            try {
                processor.consume();
            } catch (InterruptedException e) {}
        });

        t1.run();
        t2.run();
        t1.join();
        t2.join();
    }
}

Solution

  • Maybe try:

    t1.start ();
    t2.start ();
    

    instead of

    t1.run ();
    t2.run ();