Skip to content

Instantly share code, notes, and snippets.

@need4spd
Created November 29, 2012 00:39
Show Gist options
  • Save need4spd/4165874 to your computer and use it in GitHub Desktop.
Save need4spd/4165874 to your computer and use it in GitHub Desktop.
[Java] BlockingQueue를 사용한 생산자-소비자 패턴 모델 구현
package blockingqueue;
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable {
private BlockingQueue queue;
public Consumer(BlockingQueue queue) {
this.queue = queue;
}
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
String msg = queue.take();
System.out.println("메시지를 꺼냅니다. : " + msg + "[" + queue.size() + "]");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package blockingqueue;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
public class Producer implements Runnable {
private BlockingQueue queue;
public Producer(BlockingQueue queue) {
this.queue = queue;
}
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
Date d = new Date();
String msg = "메시지"+d.toString();
queue.add(msg);
System.out.println("메시지를 생성합니다. [" + queue.size() + "]");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package blockingqueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class Starter {
public static void main(String[] args) {
BlockingQueue queue = new ArrayBlockingQueue(50);
//BlockingQueue queue = new LinkedBlockingQueue();
Thread p = new Thread(new Producer(queue));
Thread c = new Thread(new Consumer(queue));
p.start();
c.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment