출처

1. BlockingQueueSample.java
 - 등록된 상품이 있으면 ConsumerThread.java 요넘이 가져가고.. 없으면 대기 시킴.
package study.concurrrency;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockingQueueSample {

 static BlockingQueueSample instance;
 
 BlockingQueue queue = new ArrayBlockingQueue(10);
 
 public synchronized static BlockingQueueSample getInstance() {
  if(instance == null)
   instance = new BlockingQueueSample();
 
  return instance;
 }
 
 public void setData(String arg) {
  try {
   queue.put(arg);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 public String getData() {
  try {
   return (String)queue.take();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }
}

2. ConsumerThread.java
 - BlockingQueueSample.java 에 등록된 상품이 있으면 무조건 가져오는 무식한 놈임. 이런 소비자만 있으면 무쟈게 행복할듯..
package study.concurrrency;

public class ConsumerThread implements Runnable {

 Thread thread;

 public void start() {
  thread = new Thread(this);
  thread.start();
 }
 
 @Override
 public void run() {
  // TODO Auto-generated method stub 

  while(true) { 
   System.out.println("aaa : " + BlockingQueueSample.getInstance().getData());
   System.out.println("aaa : " + BlockingQueueSample.getInstance().queue.size());
  
   try {
    Thread.sleep(500);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}

3. ProducerThread.java
 - 원하는 제품을 무식하게 만들어 주는 놈.
package study.concurrrency;

public class ProducerThread implements Runnable {

 Thread thread;

 String string;
 int time;
 
 public ProducerThread(String string, int time) {
  this.string = string;
  this.time = time;
 }
 public void start() {
  thread = new Thread(this);
  thread.start();
 }
 
 @Override
 public void run() {
  // TODO Auto-generated method stub 

  int index = 0;
 
  while(index<10) {
   index++;
  
   BlockingQueueSample.getInstance().setData(string + "[" + index + "]");
   try {
    Thread.sleep(time);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}

4. 테스트
ConsumerThread sample = new ConsumerThread();
sample.start();
 
ProducerThread p1 = new ProducerThread("가방", 1);
p1.start();
 
ProducerThread p2 = new ProducerThread("지갑", 1);
p2.start();

ps.
  위 예제를 참고로 Excutor를 사용해서 Thread Pool을 만들어 봐야 할듯.
Posted by 짱가쟁이