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(); } } }
java 生产者与消费者问题
时间: 2024-11-10 15:29:51