Answer the question
In order to leave comments, you need to log in
java thread synchronization? System.out.print() changed the output of the program, how?
I am learning java. Who can explain how calling wait() on a thread of control in which another thread passed by calling wait() differs from calling notify() on the same thread.Full article. I can not understand the output of the program. Why is the output not 1 0 1 0 1 0.
And an even more difficult question. Why when I put in System.out.println("Put run " +i); to the end of the put() method loop in the Producer class. (Commented out at the end) the output is changed.
public class ThreadsApp {
public static void main(String[] args) {
Store store=new Store();
Producer producer = new Producer(store);
Consumer consumer = new Consumer(store);
new Thread(producer).start();
new Thread(consumer).start();
}
}
// Класс Магазин, хранящий произведенные товары
class Store{
private int product=0;
public synchronized void get() {
while (product<1) {
try {
wait();
}
catch (InterruptedException e) {
}
}
product--;
System.out.println("Покупатель купил 1 товар");
System.out.println("Товаров на складе: " + product);
notify();
}
public synchronized void put() {
while (product>=3) {
try {
wait();
}
catch (InterruptedException e) {
}
}
product++;
System.out.println("Производитель добавил 1 товар");
System.out.println("Товаров на складе: " + product);
notify();
}
}
// класс Производитель
class Producer implements Runnable{
Store store;
Producer(Store store){
this.store=store;
}
public void run(){
for (int i = 1; i < 6; i++) {
store.put();
/// System.out.println("Put run " +i); /// Этот вызов принта меняет вывод программы на 1 0 1 0 1.. ПОЧЕМУ,??????
}
}
}
// Класс Потребитель
class Consumer implements Runnable{
Store store;
Consumer(Store store){
this.store=store;
}
public void run(){
for (int i = 1; i < 6; i++) {
store.get();
}
}
}
Answer the question
In order to leave comments, you need to log in
The problem was that Windows 10 downloaded some updates, after removing them everything worked fine
This is a typical thread race situation. notify() wakes up the thread, but does not guarantee that it will start doing work right away. Producer has time earlier, which is not surprising. When inserting a lengthy operation (output to the console) - it stops keeping up.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question