美文网首页
编写生产者/消费者模式的程序

编写生产者/消费者模式的程序

作者: 知世_5a07 | 来源:发表于2017-05-15 14:25 被阅读0次

    importjava.util.*;

    public classMyNumber {

    privateListnum=newArrayList();

    public static voidmain(String args[]) {

    MyNumber m =newMyNumber();

    newThread(newConsumer(m.getNum()),"消费者").start();

    newThread(newProducer(m.getNum()),"生产者").start();

    }

    publicList getNum() {

    returnnum;

    }

    }

    classConsumerimplementsRunnable {

    privateListnum=null;

    private intcount=0;

    publicConsumer(List list) {

    this.num= list;

    }

    @Override

    public voidrun() {

    //TODO 自动生成的方法存根while(count<100) {

    synchronized(num) {

    String name = Thread.currentThread().getName();

    if(num.size() ==0) {

    try{

    num.wait();

    }catch(InterruptedException e) {

    e.printStackTrace();

    }

    }else{

    if(num.size() >0) {

    num.remove(0);

    num.notifyAll();

    count++;

    //System.out.println(name + "取出了数字" + num.get(0) + "!!!");System.out.println("现在还剩"+num.size() +"数字!");

    }

    }

    }

    }

    }

    }

    classProducerimplementsRunnable {

    privateListnum=null;

    private intcount=0;

    publicProducer(List list) {

    this.num= list;

    }

    @Override

    public voidrun() {

    //TODO 自动生成的方法存根while(count<100) {

    synchronized(num) {

    String name = Thread.currentThread().getName();

    if(num.size() >5) {

    try{

    num.wait();

    }catch(InterruptedException e) {

    e.printStackTrace();

    }

    }else{

    String num1 =getNum();

    num.add(num1);

    num.notifyAll();

    try{

    Thread.sleep(100);

    }catch(InterruptedException e) {

    //TODO 自动生成的 catch 块e.printStackTrace();

    }

    count++;

    System.out.println(name +"添加了一个数字!");

    System.out.println("现在还有"+num.size() +"数字!");

    }

    }

    }

    }

    private staticString getNum() {

    String st;

    Random ra =newRandom();

    inta = ra.nextInt(9);

    st = String.valueOf(a);

    returnst;

    }

    }

    相关文章

      网友评论

          本文标题:编写生产者/消费者模式的程序

          本文链接:https://www.haomeiwen.com/subject/hlrhxxtx.html