Producer & Consumer 03
생산자 코드에 notifyAll()을 추가해서 풀에서 대기중인 소비자 쓰레드에게 통보하여 다시 소비를 시작하게 한다.
class Store {
public int bread; // 생산자, 소비자가 공유할 데이터
public static void main(String[] args) {
Store store = new Store();
new Producer(store).start();
new Consumer(store).start();
}
}
class Producer extends Thread {
Store store;
Producer(Store store){
this.store = store;
}
public void run() {
while(true) {
synchronized(store) {
if(store.bread<20) {
store.bread++;
System.out.println("생산==>"+store.bread);
try{
Thread.sleep(400);
}catch(InterruptedException ie){}
}else {
store.notifyAll();
}
} // synchronized 끝
}
}
}
class Consumer extends Thread {
Store store;
Consumer(Store store) {
this.store = store;
}
public void run() {
while(true) {
synchronized(store) {
while(store.bread<=10) {
try{
store.wait(); // 통지가 전달될 때까지 Wait Pool에서 대기하게 한다.
}catch(InterruptedException ie){}
}
store.bread--;
System.out.println("소비==>"+store.bread);
try{
Thread.sleep(500);
}catch(InterruptedException ie){}
} // synchronized 끝
}
}
}