본문 바로가기

Development/Programming

[Java Design Patten] Producer - Consumer 패턴

이 패턴에서는 Producer와 Consumer 그리고 Channel의 역할이 필요하다. 

Channel의 역할이 필요한 이유 Producer역할이 Consumer 역할의 처리 상황에 좌우되지 않게 하기 위함



Producer 역할


public class MakerThread extends Thread {

private final Random random;

private final Table table;

private static int id = 0;

public MakerThread (final String name, final Table table, final long seed) {

super(name);

this.table = table;

this.random = new Random(seed);

}

public void run () {

try {

while (true) {

Thread.sleep(random.nextInt(1000));

String cake = "Cake No." + nextId();

table.put(cake);

}

} catch (final InterruptedException e) {

}

}

private static synchronized int nextId() {

return id++;

}

}



Consumer 역할


public class EaterThread extends Thread {

private final Random random;

private final Table table;

public EaterThread (final String name, final Table table, final long seed) {

super (name);

this.table = table;

this.random = new Random(seed);

}

public void run () {

try

while (true) {

final String cake = table.take();

Thread.sleep(random.nextInt(1000));

}

} catch (final InterruptedException e) {

}

}

}


Channel 역할


public class Table {

private final String[] buffer;

private int tail;

private int head;

private int count;

public Table (final int count) {

this.buffer = new String[count];

this.head = 0;

this.tail = 0;

this.count = 0;

}

public synchronized void put (final String cake) throws InterruptedException {

while (count >= buffer.length) {

wait();

}

buffer[tail] = cake;

tail = (tail + 1) % buffer.length;

count++;

notifyAll();

}

public synchronized String take() throws InterruptedException {

while (count<=0) {

wait();

}

String cake = buffer[head];

head = (head + 1) % buffer.length;

count--;

notifyAll();

return cake;

}

}




public class Main {

public static void main (final String[] args) {

final Table table = new Table(3);

new MakerThread("MakerThread - 1", table, 31415).start();

new MakerThread("MakerThread - 2", table, 12342).start();

new MakerThread("MakerThread - 3", table, 1244).start();

new EaterThread("EaterThread-1", table, 12342).start();

new EaterThread("EaterThread-2", table, 12679).start();

new EaterThread("EaterThread-3", table, 23249).start();

}

}