Skip to content

Instantly share code, notes, and snippets.

@y-fedorov
Created November 24, 2021 11:43
Show Gist options
  • Save y-fedorov/3351ac309d3d4275ae8f907cce0f82a7 to your computer and use it in GitHub Desktop.
Save y-fedorov/3351ac309d3d4275ae8f907cce0f82a7 to your computer and use it in GitHub Desktop.
ReentrantLock Example code
package appstart.mymodappdemo;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
public class ReentrantLockApp {
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 {
ReentrantLock locker;
Condition condition;
private int product = 0;
Store() {
locker = new ReentrantLock(); // creating lock
condition = locker.newCondition(); // get condition related to the lock
}
public void get() {
locker.lock();
try {
// waiting for the goods (products) to appear in the store
while (product < 1)
condition.await();
product--;
System.out.println("Buyer bought 1 item");
System.out.println("Goods in stock: " + product);
// signal to all threads that awaiting that they can continue
condition.signalAll();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
} finally {
locker.unlock();
}
}
public void put() {
locker.lock();
try {
// we can store only three product items in the store
while (product >= 3)
condition.await();
product++;
System.out.println("Producer added 1 item");
System.out.println("Goods in stock: " + product);
// signal to all threads that awaiting that they can continue
condition.signalAll();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
} finally {
locker.unlock();
}
}
}
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