Created
November 24, 2021 13:47
-
-
Save y-fedorov/a12ab202d2b811149260fe6ce1471134 to your computer and use it in GitHub Desktop.
Wait Notify For Threads Java Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package appstart.mymodappdemo; | |
public class WaitNotifyForThreads { | |
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(); | |
} | |
} | |
} | |
// Класс Потребитель | |
class Consumer implements Runnable { | |
Store store; | |
Consumer(Store store) { | |
this.store = store; | |
} | |
public void run() { | |
for (int i = 1; i < 6; i++) { | |
store.get(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment