欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

马老师的WoTou生产消费线程讲解例子,wotou线程,public class

来源: javaer 分享于  点击 28690 次 点评:104

马老师的WoTou生产消费线程讲解例子,wotou线程,public class


public class ProducerConsumer {    public static void main(String[] args) {        SyncStack ss = new SyncStack();        Producer p = new Producer(ss);        Consumer c = new Consumer(ss);        new Thread(p).start();        new Thread(p).start();        new Thread(p).start();        new Thread(c).start();    }}//定义一个WoTou类,在类中有id以标记是哪个窝头,重写了toString方法class WoTou {    int id;     WoTou(int id) {        this.id = id;    }    public String toString() {        return "WoTou : " + id;    }}//定义一个篮子的对象,用于装WoTou,在类中有push方法,用于装WoTou,pop方法,用于吃WoTouclass SyncStack {    int index = 0;    WoTou[] arrWT = new WoTou[6];    /*    *wate()只有在锁定(synchronized)的时候才能使用    */    //push用于装WoTou,当WoTou数达到6时wait()休息    public synchronized void push(WoTou wt) {        while(index == arrWT.length) {            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        //唤醒瓦特()        this.notifyAll();               arrWT[index] = wt;        index ++;    }    //pop用于吃WoTou,当WoTou数为0时wait()    public synchronized WoTou pop() {        while(index == 0) {            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        this.notifyAll();        index--;        return arrWT[index];    }}//继承Runnable接口,实现run方法的Producer类,一个对象只生产20个WoTouclass Producer implements Runnable {    SyncStack ss = null;    Producer(SyncStack ss) {        this.ss = ss;    }    public void run() {        for(int i=0; i<20; i++) {            WoTou wt = new WoTou(i);            ss.push(wt);System.out.println("生产了:" + wt);            try {                Thread.sleep((int)(Math.random() * 200));            } catch (InterruptedException e) {                e.printStackTrace();            }                   }    }}//继承Runnable接口,实现run方法的Consumer类,一个对象只消费20个WoTouclass Consumer implements Runnable {    SyncStack ss = null;    Consumer(SyncStack ss) {        this.ss = ss;    }    public void run() {        for(int i=0; i<20; i++) {            WoTou wt = ss.pop();System.out.println("消费了: " + wt);            try {                Thread.sleep((int)(Math.random() * 1000));            } catch (InterruptedException e) {                e.printStackTrace();            }                   }    }}//该片段来自于http://byrx.net
相关栏目:

用户点评