java 生产者与消费者问题
package concurrency; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Storage { private int capacity; private int size; public Storage(int capacity){ this.capacity=capacity; size=0; } public synchronized void produce(){ while(size>=capacity){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } size++; System.out.println(Thread.currentThread().getName()+" produced one item, current storage:"+size); notifyAll(); } public synchronized void consume(){ while(size<=0){ try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } size--; System.out.println(Thread.currentThread().getName()+" consumed one item, current storage:"+size); notifyAll(); } public static void main(String [] args){ Storage storage = new Storage(10); startProductThread(storage); startConsumThread(storage); } /** * 开启生产者线程 */ public static void startProductThread(Storage storage){ System.out.println("--生产者线程执行开始--"); int pThreadSize = 10; ExecutorService pool = Executors.newFixedThreadPool(pThreadSize); for(int i=0;i<pThreadSize;i++){ Producer productThread = new Producer(storage); Thread thread = new Thread(productThread); pool.execute(thread); } System.out.println("--生产者线程执行结束--"); } /** * 开启消费者线程 */ public static void startConsumThread(Storage storage){ System.out.println("--消费者线程执行开始--"); int pThreadSize = 10; ExecutorService pool = Executors.newFixedThreadPool(pThreadSize); for(int i=0;i<pThreadSize;i++){ Consumer consumeThread = new Consumer(storage); Thread thread = new Thread(consumeThread); pool.execute(thread); } System.out.println("--消费者线程执行结束--"); } } class Producer implements Runnable { Storage storage; public Producer(Storage storage){ this.storage=storage; } @Override public void run(){ while(true){ try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } storage.produce(); } } } class Consumer implements Runnable{ Storage storage; public Consumer(Storage storage){ this.storage=storage; } @Override public void run() { while(true){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } storage.consume(); } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。