Мой код останавливается на «Производитель запущен». Почему wait () не освобождает блокировку? Я использую тот же объект в синхронизированном разделе, но он не работает.
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");
}
}
}
Когда я запускаю этот код в разных потоках, я использую один и тот же объект Processor
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();
}
}