生產者消費者3種實現方式


生產者/消費者問題的多種實現方式 
1.使用阻塞隊列實現
   // Producer Class in java
class Producer implements Runnable {
private final BlockingQueue sharedQueue;
public Producer(BlockingQueue sharedQueue) {
this.sharedQueue = sharedQueue; }
public void run() {
for (int i = 0; i < 10; i++) {
try {
System.out.println("Produced: " + i); sharedQueue.put(i);
} catch (InterruptedException ex) {
System.out.println(ex); }
} }
}
// Consumer Class in Java
class Consumer implements Runnable {
private final BlockingQueue sharedQueue;
public Consumer(BlockingQueue sharedQueue) {
this.sharedQueue = sharedQueue; }
public void run() { while (true) {
try {
int i = (Integer) sharedQueue.take(); System.out.println("Consumed: " + i);
} catch (InterruptedException ex) {
System.out.println(ex); }
} }
}
public class ProducerConsumerPattern {
public static void main(String args[]) { // Creating shared object
BlockingQueue sharedQueue = new LinkedBlockingQueue();
      // Creating Producer and Consumer Thread
Thread prodThread = new Thread(new Producer(sharedQueue)); Thread consThread = new Thread(new Consumer(sharedQueue));
 // Starting producer and Consumer thread
prodThread.start();
consThread.start(); }
}
2.使用 Object 的 wait()和 notify()實現
queue = new PriorityQueue<Integer>(10);//
class Consumer extends Thread {
public void run() { while (true) {
synchronized (queue) {
while (queue.size() == 0) {//隊列空的條件下阻塞
try { queue.wait();
} catch (InterruptedException e) { e.printStackTrace();
queue.notify(); }
}
queue.poll(); // 每次移走隊首元素 queue.notify();
} }
} }
class Producer extends Thread {
public void run() { while (true) {
  
  
PriorityQueue<Integer>
 充當緩衝區
  塞
synchronized (queue) {
while (queue.size() == 10) {//隊列滿了的條件下阻
try { queue.wait();
} catch (InterruptedException e) { e.printStackTrace();
queue.notify(); }
}
queue.offer(1); // 每次插入一個元素 queue.notify();
} }
} }
3.使用 Condition 實現
private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(10);
private Lock lock = new ReentrantLock();
private Condition notFull = lock.newCondition(); private Condition notEmpty = lock.newCondition();
class Consumer extends Thread {
public void run() { while (true) {
lock.lock(); try {
while (queue.size() == 0) { try {
notEmpty.await();
} catch (InterruptedException e) {
e.printStackTrace(); }
}
queue.poll(); // 每次移走隊首元素 notFull.signal();
} finally {
lock.unlock(); }
} }
}

class Producer extends Thread {
public void run() { while (true) {
lock.lock(); try {
while (queue.size() == 10) { try {
notFull.await();
} catch (InterruptedException e) {
e.printStackTrace(); }
}
queue.offer(1); // 每次插入一個元素 notEmpty.signal();
} finally {
lock.unlock(); }
} }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章