하루의 대학원 도전기

[JAVA] BlockingQueue를 이용한 Producer-Consumer 예제 본문

프로그래밍/Java

[JAVA] BlockingQueue를 이용한 Producer-Consumer 예제

내가하루다 2021. 12. 8. 15:20
728x90

출처 ㅣ: https://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html

 

BlockingQueue (Java 2 Platform SE 5.0)

 boolean offer(E o, long timeout, TimeUnit unit)           Inserts the specified element into this queue, waiting if necessary up to the specified wait time for space to become available.

docs.oracle.com

 class Producer implements Runnable {
   private final BlockingQueue queue;
   Producer(BlockingQueue q) { queue = q; }
   public void run() {
     try {
       while(true) { queue.put(produce()); }
     } catch (InterruptedException ex) { ... handle ...}
   }
   Object produce() { ... }
 }

 class Consumer implements Runnable {
   private final BlockingQueue queue;
   Consumer(BlockingQueue q) { queue = q; }
   public void run() {
     try {
       while(true) { consume(queue.take()); }
     } catch (InterruptedException ex) { ... handle ...}
   }
   void consume(Object x) { ... }
 }

 class Setup {
   void main() {
     BlockingQueue q = new SomeQueueImplementation();
     Producer p = new Producer(q);
     Consumer c1 = new Consumer(q);
     Consumer c2 = new Consumer(q);
     new Thread(p).start();
     new Thread(c1).start();
     new Thread(c2).start();
   }
 }

 

 

Runnable 인터페이스를 implents하는 방법으로 구현된 

Producer Consumer- 생산자 소비자 예제입니다. 

BlockingQueue는 큐가 꽉 찼을 때의 삽입시도, 비었을 때의 추출 시도를 막아주기 때문에

Thread-Safe합니다.

728x90