ivanov.john
ivanov.john

Reputation: 11

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();
    }
}

Upvotes: 0

Views: 53

Answers (2)

Naya
Naya

Reputation: 870

The problem here is that you call run() methods on Threads. You should use start() if you're about to run it in separate thread.

Upvotes: 0

BingLi224
BingLi224

Reputation: 462

Maybe try:

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

instead of

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

Upvotes: 2

Related Questions