简单介绍管道法:
生产者生产数据输送到管道,消费者从管道拿出数据,管道为空消费者等待,管道满生产者生产,消费者消费生产者生产,生产者生产消费者消费。
public class Corn { //要生产的产品 }
public class Buffer { private int count=0; //产品计数器 private Corn corn[]=new Corn[10]; //缓冲区容量,缓冲区满生产等待,缓冲区空消费者等待 /*生产数据*/ public synchronized void produce(Corn corn){ //注意:wait()只能在同步块/同步方法中使用 if(count>=this.corn.length){ //缓冲区满 try { //线程等待 this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.corn[count]=corn; //可以生产数据 count++; this.notifyAll(); //通知消费 } /*取出数据*/ public synchronized Corn getCorn(){ if(count==0){ //缓冲区空 try { //线程等待 this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } count--; //可以取出数据 this.notifyAll(); //通知生产 return corn[count]; } }
/** * 生产者类 */ public class Produce implements Runnable{ private Buffer buffer; public Produce(Buffer buffer) { this.buffer = buffer; } @Override public void run() { for (int i = 1; i <= 100; i++) { buffer.produce(new Corn()); System.out.println("生产第"+i+"个产品"); } } }
/** * 消费者类 */ public class Customer implements Runnable { private Buffer buffer; public Customer(Buffer buffer) { this.buffer = buffer; } @Override public void run() { for (int i = 1; i <= 100; i++) { buffer.getCorn(); System.out.println("得到第"+i+"份产品"); } } }
/** * 主类 */ public class Test { public static void main(String[] args) { Buffer buffer=new Buffer(); /*开启生产者和消费者进程*/ new Thread(new Produce(buffer)).start(); new Thread(new Customer(buffer)).start(); } }