多執行緒:生產者消費者模型
阿新 • • 發佈:2022-04-20
1、阻塞佇列實現
public class Main { private static final int capacity=2, ptime=6, ctime=6; private static BlockingQueue<Integer> storage=new LinkedBlockingQueue<>(capacity); private static Integer count=0; static class Producer implements Runnable { @Override public void run() { for (int i = 0; i < ptime; i++) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } try { //這裡上鎖是為了保證put和列印是原子的,如果不需要列印,可以不上鎖。 synchronized (count) { storage.put(count); System.out.println("Producer:" + Thread.currentThread().getName() + " put: " + count++); } } catch (InterruptedException e) { e.printStackTrace(); } } } } static class Consumer implements Runnable { @Override public void run() { for (int i = 0; i < ctime; i++) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } try { System.out.println("Consumer:" + Thread.currentThread().getName() + " take: " + storage.take()); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { new Thread(new Consumer(),"C1").start(); new Thread(new Consumer(),"C2").start(); new Thread(new Producer(),"P1").start(); new Thread(new Producer(),"P2").start(); new Thread(new Producer(),"P3").start(); } }
2、Synchronized實現
class Storage { final int storageSize; private int countNow = 0; Storage(int storageSize) { this.storageSize = storageSize; } public void produce() { System.out.print("Producer " + Thread.currentThread().getName()); if (countNow < storageSize) { countNow++; System.out.print(" ##SUCCESS##, STORAGE:" + countNow); } else { System.out.print(" ##FAILTED:STORAGE FULL##"); } System.out.println(" Producer=========================="); } public void consume() { System.out.print("Consumer " + Thread.currentThread().getName()); if (countNow > 0) { countNow--; System.out.println(" ##SUCCESS##, STORAGE:" + countNow); } else { System.out.println(" ##FAILTED: STORAGE EMPTY##"); } } public int getCount(){ return countNow; } } public class Main { private static Storage storage; static class Producer implements Runnable { @Override public void run() { for (int i = 0; i < storage.storageSize; i++) { synchronized (storage) { storage.produce(); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } } } static class Consumer implements Runnable { @Override public void run() { for (int i = 0; i < storage.storageSize; i++) { synchronized (storage) { storage.consume(); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } } } public static void main(String[] args) { storage=new Storage(10); new Thread(new Producer(),"P1").start(); new Thread(new Producer(),"P2").start(); new Thread(new Producer(),"P3").start(); new Thread(new Consumer(),"C1").start(); new Thread(new Consumer(),"C2").start(); } }
生產者和消費者都對同一倉庫物件上鎖。