Created
August 1, 2020 19:56
-
-
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
This file contains 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
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