并发编程之的虚假唤醒和精准唤醒的详细解析

虚假唤醒

例子

wait()是object类自带的方法,在jdk有介绍,有可能出现中断、虚假唤醒

也就是在下面的例子中

if(number != 0){
 this.wait();
}

当线程成功进入if语句块中,发生了中断,cpu跑去调度别的进程了,再次调度这个线程的时候,应该需要再经历一次if的判断,但是并没有这样做。

于是下面的程序运行结果:

/**
 * @author zkw
 * @Description TODO
 * 
 */
public class ThreadWaitNotify {
    public static void main(String[] args) {
        Resource resource = new Resource();
        //increment
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    resource.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A-1").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    resource.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A-2").start();
​
        //decrement
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    resource.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B-1").start();
        new Thread(()->{
            try {
                resource.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"B-2").start();
    }
​
}
​
class Resource{
    private int number = 0;
​
    //number++
    public synchronized void increment() throws InterruptedException {
        if(number != 0){
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName()+":"+number);
        this.notifyAll();
    }
    //number--
    public synchronized void decrement() throws InterruptedException {
        if(number == 0){
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName()+":"+number);
        this.notifyAll();
    }
​
​
}

解决办法

按照jdk文档的指示,应该将if换成while

      
  while(number == 0){
            this.wait();
        }

修改后,正确的运行结果如下:

精准唤醒

JUC那套 lock、await、signal和 Object那套 synchronized、wait、notify的区别:

condition这一套能实现精确唤醒某一个线程,而不是像notifyAll那样唤醒全部线程。

下面这个例子中,一共创建了三个Condition,可以根据业务对这三个Condition依次唤醒。来达到精准唤醒的功能

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
​
/**
 * @author zkw
 * @Description 线程顺序访问
 *  多线程之间的顺序调用  A-》B-》C
 *  三个线程启动,要求如下:
 *  AA打印5次,BB打印10次,CC打印15次
 *  接着
 *  AA打印5次,BB打印10次,CC打印15次
 *  ....来10轮
 *
 *  1 高内聚低耦合的前提下,线程 操作 资源类
 *  2 判断/干活/通知
 *  3 多线程交互中,必须要防止多线程的虚假唤醒,也即(判断只用while不用if)
 *  4 标志位
 * 
 */
public class ThreadOrderAccess {
    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    shareResource.printf5();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"Thread1").start();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    shareResource.printf10();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"Thread2").start();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    shareResource.printf15();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"Thread3").start();
    }
}
​
class ShareResource{
    private int number = 1; //1:A    2:B    3C
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    public void printf5() throws InterruptedException {
        lock.lock();
        try {
            while (number!=1){
                condition1.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName()+"--AA");
            }
            number = 2;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
​
    public void printf10() throws InterruptedException {
        lock.lock();
        try {
            while (number!=2){
                condition2.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName()+"--BB");
            }
            number = 3;
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
​
    public void printf15() throws InterruptedException {
        lock.lock();
        try {
            while (number!=3){
                condition3.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName()+"--CC");
            }
            number = 1;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
​

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

向着五星的方向

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值