본문 바로가기

Java SE/Producer & Consumer 00

Producer & Consumer 00

생산자와 소비자가 병행처리되고 있지만, 소비자 쓰레드가 먼저 시작되면 0 이하로 내려가는 문제가 생긴다.

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) {
     store.bread++;
     System.out.println("생산==>"+store.bread);
     try{
      Thread.sleep(400);
     }catch(InterruptedException ie){}
   } // synchronized 끝
  }
 }
}


class Consumer extends Thread {
 Store store;

 Consumer(Store store) {
  this.store = store;
 }

 public void run() {
  while(true) {
   synchronized(store) {
     store.bread--;
     System.out.println("소비==>"+store.bread);
     try{
      Thread.sleep(500);
     }catch(InterruptedException ie){}
   } // synchronized 끝
  }
 }
}