334 - 线程通信问题

应用场景:生产者和消费者问题

        假设仓库中只能存放一件产品,生产者将生产出来的产品放入仓库,消费者将仓库中产品取走消费;

        如果仓库中没有产品,则生产者将产品放入仓库,否则停止生产并等待,直到仓库中的产品被消费者取走为止;

        如果仓库中放有产品,则消费者可以将产品取走消费,否则停止消费并等待,直到仓库中再次放入产品为止。

 代码结果展示:

代码:

1、商品:属性:品牌 ,名字

2、线程1:生产者

3、线程2:消费者

分解1

出现问题:

1.生产者和消费者没有交替输出

2.打印数据错乱,如:

“哈尔滨 - null”,

“ 费列罗啤酒”,

“哈尔滨巧克力 ”    ,            原因:没有加同步

代码示例:

(1)商品类Product

package test13_thread_communication;

/**
 * @Auther: zhoulz
 * @Description: test13_thread_communication
 * @version: 1.0
 */
public class Product { //商品类
    //品牌
    private String brand;
    //名字
    private String name;

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

(2)生产者线程(类) ProducerThread

package test13_thread_communication;

/**
 * @Auther: zhoulz
 * @Description: test13_thread_communication
 * @version: 1.0
 */
public class ProducerThread extends Thread{ //生产者线程
    //共享商品
    private Product p;

    //构造器
    public ProducerThread(Product p) {
        this.p = p;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {//生产10个商品, i:生产的次数
            if (i % 2 == 0){
                //生产费列罗巧克力
                p.setBrand("费列罗");
                //如果想在生产之间,模拟一下线程的切换
                //可以加一个 线程失眠:(然后加一个异常捕获)
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                p.setName("巧克力");
            }else {
                //生产哈尔滨啤酒
                p.setBrand("哈尔滨");
                //同理,下面也加一个
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                p.setName("啤酒");
            }
            //将生产信息做一个打印
            System.out.println("生产者生产了:" + p.getBrand() +"---"+ p.getName());
        }
    }
}

(3)消费者线程(类)CustomerThread

package test13_thread_communication;

/**
 * @Auther: zhoulz
 * @Description: test13_thread_communication
 * @version: 1.0
 */
public class CustomerThread extends Thread{//消费者线程
    //共享商品
    private Product p;

    public CustomerThread(Product p) {
        this.p = p;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.println("消费者消费了:" + p.getBrand() + "---" + p.getName());
        }
    }
}

(4)测试类Test1

package test13_thread_communication;

/**
 * @Auther: zhoulz
 * @Description: test13_thread_communication
 * @version: 1.0
 */
public class Test1 {
    public static void main(String[] args) {
        //共享的商品
        Product p = new Product();
        //创建生产者和消费者线程:
        ProducerThread pt = new ProducerThread(p);
        CustomerThread ct = new CustomerThread(p);

        pt.start();
        ct.start();
    }
}

分解2

针对上面出现的问题:

1)生产者和消费者没有交替输出;

2)打印数据错乱 —— 原因:没有加同步。

分解2 —— 来解决数据错乱问题:

【1】利用同步代码块解决问题

(1)商品类Product、(4)测试类Test1 —— 不变

注:锁用的是——共享商品:p

(2)生产者线程(类) ProducerThread

package test13_thread_communication;

/**
 * @Auther: zhoulz
 * @Description: test13_thread_communication
 * @version: 1.0
 */
public class ProducerThread extends Thread{ //生产者线程
    //共享商品
    private Product p;

    //构造器
    public ProducerThread(Product p) {
        this.p = p;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {//生产10个商品, i:生产的次数
            synchronized (p){
                if (i % 2 == 0){
                    //生产费列罗巧克力
                    p.setBrand("费列罗");
                    //如果想在生产之间,模拟一下线程的切换
                    //可以加一个 线程失眠:(然后加一个异常捕获)
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    p.setName("巧克力");
                }else {
                    //生产哈尔滨啤酒
                    p.setBrand("哈尔滨");
                    //同理,下面也加一个
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    p.setName("啤酒");
                }
                //将生产信息做一个打印
                System.out.println("生产者生产了:" + p.getBrand() +"---"+ p.getName());
            }
        }
    }
}

(3)消费者线程(类)CustomerThread

package test13_thread_communication;

/**
 * @Auther: zhoulz
 * @Description: test13_thread_communication
 * @version: 1.0
 */
public class CustomerThread extends Thread{//消费者线程
    //共享商品
    private Product p;

    public CustomerThread(Product p) {
        this.p = p;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            synchronized (p){
                System.out.println("消费者消费了:" + p.getBrand() + "---" + p.getName());
            }
        }
    }
}

结果 —— 解决了数据错乱问题。

【2】利用同步方法解决问题

        这里,​​​​​不能单纯地将可能出现异常的代码提取/剪切出来,然后封装成一个方法,同时加上synchronized(以及static)修饰,最后在原来代码的地方调用该同步方法 就行了。

       因为,这么锁的话还是没有锁住统一的东西,锁的分别是生产者和消费者的锁,不是一把锁。

即还是之前的问题:锁必须是同一把锁、唯一的一把锁,生产者和消费者共同操作一把锁。

怎么解决??

现在,是想锁住这个商品 Product  p,

所以,现在把方法都提到 Product 类中:即 把公共的代码(可能出现异常的)提过来,

然后放到一个新的方法(synchronized修饰的,并进行代码调整)中:

代码示例:

(1)商品类Product

package test13_2;

/**
 * @Auther: zhoulz
 * @Description: test13_thread_communication
 * @version: 1.0
 */
public class Product { //商品类
    //品牌
    private String brand;
    //名字
    private String name;

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //把线程类中的公共代码块提取过来 (分为生产商品、消费商品)
    //生产商品:
    public synchronized void setProduct(String brand, String name){
        //调整:
        //去掉 if-else,(if-else结构放在原来线程类中代码块的位置)
        //并把 "费列罗"、"巧克力" 作为参数传进来
        //把p换成this
        //最后,在线程类中原来代码块的位置调用该方法,并且是用共享的商品p去调用

        //生产费列罗巧克力
        this.setBrand(brand);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.setName(name);

        //将生产信息做一个打印
        System.out.println("生产者生产了:" + this.getBrand() +"---"+ this.getName());
    }

    //消费商品
    public synchronized void getProduct(){
        System.out.println("消费者消费了:" + this.getBrand() + "---" + this.getName());
    }
}

(2)生产者线程(类) ProducerThread

package test13_2;

/**
 * @Auther: zhoulz
 * @Description: test13_thread_communication
 * @version: 1.0
 */
public class ProducerThread extends Thread{ //生产者线程
    //共享商品
    private Product p;

    //构造器
    public ProducerThread(Product p) {
        this.p = p;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {//生产10个商品, i:生产的次数
            if (i % 2 == 0){
                p.setProduct("费列罗","巧克力");
            }/*else{
                p.setProduct("哈尔滨","啤酒");
            }*/
        }
    }
}

上面生产 “ 哈尔滨啤酒” 的代码忘记了,后面记得加上。 

(3)消费者线程(类)CustomerThread

package test13_2;

/**
 * @Auther: zhoulz
 * @Description: test13_thread_communication
 * @version: 1.0
 */
public class CustomerThread extends Thread{//消费者线程
    //共享商品
    private Product p;

    public CustomerThread(Product p) {
        this.p = p;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) { // i-消费次数
            p.getProduct();
        }
    }
}

(4)测试类Test1  —— 没有变

运行结果:  —— 同样也解决了数据错乱问题

分解3

【1】原理

【2】代码

(1)商品类Product

package test13_3;

/**
 * @Auther: zhoulz
 * @Description: test13_thread_communication
 * @version: 1.0
 */
public class Product { //商品类
    //品牌
    private String brand;
    //名字
    private String name;

    //引入一个灯:true:红色  false 绿色
    boolean flag = false;//默认情况下没有商品,让生产者先生产,然后消费者再消费

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    //生产商品:
    public synchronized void setProduct(String brand, String name){
        if (flag == true){ //灯是红色,证明有商品,生产者不生产,等着消费者消费
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //灯是绿色的,就生产
        this.setBrand(brand);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.setName(name);

        //将生产信息做一个打印
        System.out.println("生产者生产了:" + this.getBrand() +"---"+ this.getName());

        //生产完以后,灯变色:变成红色:
        flag = true;
        //告诉消费者赶紧来消费
        notify();
    }

    //消费商品
    public synchronized void getProduct(){
        if (!flag){//或者用flag == false 没有商品,等待生产者生产
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //有商品,则消费:
        System.out.println("消费者消费了:" + this.getBrand() + "---" + this.getName());

        //消费完,灯变色:
        flag = false;
        //通知生产者生产:
        notify();
    }
}

(2)生产者线程(类) ProducerThread

(3)消费者线程(类)CustomerThread

(4)测试类Test1                                               ——  这3处代码都没变。

(注: 分解3的代码在分解2的代码基础上进行改进的)

结果: 达成要求:生产一个、消费一个

 【3】原理 —— 锁池、等待池

注意:wait方法和notify方法  是必须放在同步方法或者同步代码块中才生效的 (因为在同步的基础上进行线程的通信才是有效的)

注意:sleep和wait的区别:sleep进入阻塞状态没有释放锁,wait进入阻塞状态但是同时释放了锁

【4】线程生命周期完整图 - 补全

Loc锁情况下的线程通信 

        Condition是在Java 1.5中才出现的,它用来替代传统的Object的wait()、notify()实现线程间的协作,相比使用Object的wait()、notify(),使用Condition1的await()、signal()这种方式实现线程间协作更加安全和高效。 

        它的更强大的地方在于:能够更加精细的控制多线程的休眠与唤醒。对于同一个锁,我们可以创建多个Condition,在不同的情况下使用不同的Condition ,一个Condition包含一个等待队列。一个Lock可以产生多个Condition,所以可以有多个等待队列。

        在Object的监视器模型上,一个对象拥有一个同步队列和等待队列,而Lock(同步器)拥有一个同步队列和多个等待队列。 

        Object中的wait(),notify(),notifyAll()方法是和"同步锁"(synchronized关键字)捆绑使用的;

        而Condition是需要与"互斥锁"/"共享锁"捆绑使用的。 

        调用Condition的await()、signal()、signalAll()方法,都必须在lock保护之内,就是说必须在lock.lock()和lock.unlock之间才可以使用 。

· Conditon中的await()对应Object的wait();

· Condition中的signal()对应Object的notify();

· Condition中的signalAll()对应Object的notifyAll()。

   void await()  throws InterruptedException 

   造成当前线程在接到信号或被中断之前一直处于等待状态。

        与此 Condition 相关的锁以原子方式释放,并且出于线程调度的目的,将禁用当前线程,且在发生以下四种情况之一 以前,当前线程将一直处于休眠状态:

其他某个线程调用此 Condition 的 signal() 方法,并且碰巧将当前线程选为被唤醒的线程;

或者其他某个线程调用此 Condition 的 signalAll() 方法;

或者其他某个线程中断当前线程,且支持中断线程的挂起;

或者发生“虚假唤醒”。

        在所有情况下,在此方法可以返回当前线程之前,都必须重新获取与此条件有关的锁。在线程返回时,可以保证它保持此锁。

void signal()  ——  唤醒一个等待线程。        

        如果所有的线程都在等待此条件,则选择其中的一个唤醒。在从 await 返回之前,该线程必须重新获取锁。

void signalAll()  ——  唤醒所有等待线程。

        如果所有的线程都在等待此条件,则唤醒所有线程。在从 await 返回之前,每个线程都必须重新获取锁。    

更改代码:

(1)商品类Product

package test14_Lock_communication;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther: zhoulz
 * @Description: test13_thread_communication
 * @version: 1.0
 */
public class Product { //商品类
    //品牌
    private String brand;
    //名字
    private String name;

    //声明一个Lock锁:
    Lock lock = new ReentrantLock();
    //搞一个生产者的等待队列: (条件队列)
    Condition produceCondition = lock.newCondition();
    //搞一个消费者的等待队列:
    Condition consumeCondition = lock.newCondition();

    //引入一个灯:true:红色  false 绿色
    boolean flag = false;//默认情况下没有商品,让生产者先生产,然后消费者再消费

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //生产商品:
    //现在用的是Lock了,
    //需要先把synchronized 关键词去掉
    public void setProduct(String brand, String name){
        //先 把锁加上
        lock.lock();
        //再把下面if后面的代码放到try-catch中,并把关锁放在finally中
        try {
            if (flag == true){ //灯是红色,证明有商品,生产者不生产,等着消费者消费
                try {
                    //wait();//不再用wait()了,其是阻塞的,且必须要和synchronized配合使用
                    //生产者阻塞,一旦阻塞,则生产者进入等待队列中
                    produceCondition.await();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //灯是绿色的,就生产
            this.setBrand(brand);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.setName(name);

            //将生产信息做一个打印
            System.out.println("生产者生产了:" + this.getBrand() +"---"+ this.getName());

            //生产完以后,灯变色:变成红色:
            flag = true;
            //告诉消费者赶紧来消费
            //notify(); //同理,也不能用notify()了
           consumeCondition.signal();
        }finally{
            lock.unlock();
        }

    }

    //消费商品
    public void getProduct(){
        lock.lock();
        try {
            if (!flag){//或者用flag == false 没有商品,等待生产者生产
                try {
                    //wait();
                    //消费者等待,则消费者线程进入到等待队列
                    consumeCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //有商品,则消费:
            System.out.println("消费者消费了:" + this.getBrand() + "---" + this.getName());
            //消费完,灯变色:
            flag = false;
            //通知生产者生产:
            //notify();
            produceCondition.signal();
        }finally {
            lock.unlock();
        }
    }
}

(2)生产者线程(类) ProducerThread

(3)消费者线程(类)CustomerThread

(4)测试类Test1                                               ——  这3处代码都没变。

运行结果—— 正常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值