Skip to content

Instantly share code, notes, and snippets.

@Audhil
Created August 1, 2020 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Audhil/6790ad34f57e34456cffe62f5caa06f8 to your computer and use it in GitHub Desktop.
Save Audhil/6790ad34f57e34456cffe62f5caa06f8 to your computer and use it in GitHub Desktop.
wait() & notify() of Object class - for ref: https://www.youtube.com/watch?v=A1tnVMpWHh8
public class WaitNotifyDemo {
public static void main(String[] args) {
Q q = new Q();
new Producer(q);
new Consumer(q);
}
static class Q {
private int num;
private boolean valueSet = false;
public synchronized void put(int num) {
while (valueSet) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("put: " + num);
this.num = num;
valueSet = true;
notify();
}
public synchronized void get() {
while (!valueSet) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("get: " + num);
valueSet = false;
notify();
}
}
static class Producer implements Runnable {
private Q q;
public Producer(Q q) {
this.q = q;
Thread thread = new Thread(this, "Producer");
thread.start();
}
@Override
public void run() {
int i = 0;
while (true) {
q.put(i++);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class Consumer implements Runnable {
private Q q;
public Consumer(Q q) {
this.q = q;
Thread thread = new Thread(this, "Consumer");
thread.start();
}
@Override
public void run() {
while (true) {
q.get();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment