码迷,mamicode.com
首页 > 编程语言 > 详细

多线程-线程间通信_生产者和消费者

时间:2019-04-13 20:25:34      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:结果   art   consumer   出错   pac   etc   getc   生产者   wait   

package 多线程.线程间通信_生产者和消费者;

public class Phone {
    private String  type;
    private String  color;
    boolean f =true;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Phone() {
    }

    /*
    * 生产
    * */
    public synchronized void addPhone(String type,String color) throws InterruptedException {
        while (!f){  //这里循环需要用while而不用if  避免多线程出错
            this.wait();
        }
        setType(type);
        setColor(color);

        f=false;
        this.notifyAll();
    }
    /*
    *
    * 获取
    * */
    public synchronized void getPhone() throws InterruptedException {
        while (f){
            this.wait();
        }
        System.out.println(getType()+"-----"+getColor());
        f=true;
        this.notify();

    }
}
package 多线程.线程间通信_生产者和消费者;
/*
* 生产者
* */
public class Producer implements Runnable {
    private Phone phone;

    public Producer(Phone phone) {
        this.phone = phone;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            if (i % 2 == 0) {
                try {
                    phone.addPhone("洛基亚", "黑色");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    phone.addPhone("苹果", "金色");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }
}
package 多线程.线程间通信_生产者和消费者;
/*
* 消费者
*
* */
public class Consumer implements Runnable {
    private Phone phone;

    public Consumer(Phone phone) {
        this.phone = phone;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                phone.getPhone();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
package 多线程.线程间通信_生产者和消费者;

public class demo01 {
    public static void main(String[] args) {
        Phone phone =new Phone();

        Producer producer =new Producer(phone);
        Thread t1 =new Thread(producer);
        t1.start();

        Consumer consumer =new Consumer(phone);
        Thread t2 =new Thread(consumer);
        t2.start();
    }
}

结果:

洛基亚-----黑色
苹果-----金色
洛基亚-----黑色
苹果-----金色
洛基亚-----黑色

 

 

多线程-线程间通信_生产者和消费者

标签:结果   art   consumer   出错   pac   etc   getc   生产者   wait   

原文地址:https://www.cnblogs.com/houtian2333/p/10702691.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!