class Producer extends Thread{
private final Queue<Integer> sharedQueue;
public Producer(Queue<Integer> sharedQueue) {
super("Producer");
this.sharedQueue = sharedQueue;
}
@Override
public void run(){
for(int i = 1 ; i<5;i++){
synchronized (sharedQueue) {
while(sharedQueue.size() > 0){
try {
System.out.println("Queue is full, waiting!");
sharedQueue.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("producing : " + i);
sharedQueue.add(i);
sharedQueue.notify();
}
}
}
}
class Counsumer extends Thread{
private final Queue<Integer> sharedQueue;
public Counsumer(Queue<Integer> sharedQueue) {
super("Counsumer");
this.sharedQueue = sharedQueue;
}
@Override
public void run(){
while(true){
synchronized (sharedQueue) {
while(sharedQueue.size() == 0){
try {
System.out.println("Queue is empty, waiting~~");
sharedQueue.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
int number = sharedQueue.remove();
System.out.println("consuming : " + number);
sharedQueue.notify();
if(number == 3){break; }
}
}
}
}
public class Main {
* @param args
*/
public static void main(String[] args) {
Queue<Integer> sharedQueue = new LinkedList<>();
new Producer(sharedQueue).start();
new Counsumer(sharedQueue).start();
}
}
* output:
* producing : 1
* Queue is full, waiting!
* consuming : 1
* Queue is empty, waiting~~
* producing : 2
* Queue is full, waiting!
* consuming : 2
* Queue is empty, waiting~~
* producing : 3
* Queue is full, waiting!
* consuming : 3
* producing : 4
*/