任务说明:
生产者(Productor)将产品交给店员(Clerk),
而消费者(Customer)从店员处取走产品,
店员一次只能持有固定数量的产品(比如:20),
如果生产者试图生产更多的产品,店员会叫生产者停一下,如果店中有空位放产品了再通知生产者继续生产;
如果店中没有产品了,店员会告诉消费者等一下,如果店中有产品了再通知消费者来取走产品。
使用Runnable接口完成该任务,代码如下:
package testThread; /*共享数据*/ class Clerk{ int product; public synchronized void pruduceProuct(){ if (product < 20){ product++; System.out.print("Produce " + product); notifyAll(); } else{ try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public synchronized void consumerProduct(){ if (product > 0){ product--; System.out.print("Consumer" + product); notifyAll(); } else{ try{ wait(); } catch (InterruptedException e){ e.printStackTrace(); } } } } /*生产者,使用Runable接口*/ class Producer implements Runnable{ Clerk clerk; public Producer(Clerk clerk) { this.clerk = clerk; } @Override public void run() { // TODO Auto-generated method stub System.out.print(""); while(true){ clerk.pruduceProuct(); } } } /* 消费者,使用Runable接口 */ class Consumer implements Runnable{ Clerk clerk; public Consumer(Clerk clerk){ this.clerk = clerk; } @Override public void run() { // TODO Auto-generated method stub while(true){ clerk.consumerProduct(); } } } /*测试代码*/ public class Consumer_Producer { public static void main(String[] arg){ Clerk clerk = new Clerk(); Producer producer = new Producer(clerk); Consumer consumer = new Consumer(clerk); Thread productThread = new Thread(producer); Thread consumerThread = new Thread(consumer); productThread.setName("Producer"); consumerThread.setName("Consumer"); productThread.start(); consumerThread.start(); } }
本文出自 “小鱼随笔” 博客,请务必保留此出处http://kevinyu.blog.51cto.com/837500/1623135
原文:http://kevinyu.blog.51cto.com/837500/1623135