Java——生产者消费者多线程实现

来源:互联网 发布:手机移动网络开关在哪 编辑:程序博客网 时间:2024/06/06 09:16
/*生产者消费者问题,这里实现的是生产一个,消费一个,生产一个,消费一个生产者有生产任务消费者有消费任务生产和消费可以同时执行所以使用多线程需要描述生产任务需要描述消费任务生产的是产品消费的是产品需要描述产品*///描述产品class Product{    private String name;    private int count;    private boolean flag;    //生产产品的功能    public synchronized void produce(String name){        if(flag){            try{wait();}catch(InterruptedException e){e.printStackTrace();}        }        this.name = name+"..."+count;        System.out.println(Thread.currentThread().getName()+"生产了..."+this.name);        count++;        flag = true;        notify();    }    //生产的时候不能消费,消费的时候不能生产,否则会出现安全问题    //消费产品的功能    public synchronized void consume(){        if(!flag){            try{wait();}catch(InterruptedException e){e.printStackTrace();}        }        System.out.println(Thread.currentThread().getName()+"...消费了..."+this.name);        flag = false;        notify();    }}//生产任务class Producer implements Runnable{    private Product pro;    public Producer(Product pro){        this.pro = pro;    }    public void run(){        while(true){            pro.produce("笔记本");        }    }}//消费任务class Consumer implements Runnable{    private Product pro;    public Consumer(Product pro){        this.pro = pro;    }    public void run(){        while(true){            pro.consume();        }    }}class test{    public static void main(String[] args){        Product pro = new Product();        Producer producer = new Producer(pro);        Consumer consumer = new Consumer(pro);        Thread t1 = new Thread(producer);        Thread t2 = new Thread(consumer);        t1.start();        t2.start();    }}
原创粉丝点击