Java多线程 wait(),notify(),notifyAll()

多线程中的常见方法

面试中的常见问题

  • 为什么线程通信的方法wait(),notify(),和notifyAll()被定义在Object类中,sleep定义在Thread类里?
  • 用3种方法实现生产者模式
  • JavaSE8和Java1.8和JDK8是什么关系,是同一个东西吗?
  • join,sleep和wait期间线程的状态分别是什么,为什么?

Thread与Object中与多线程常见的方法

  • Thread
    • sleep相关
    • join
    • yield
    • currentThread
    • start,run相关
    • interrtupt
    • stop
    • suspend,resuem
  • Object
    • wait,notify,notifyAll

Object中的wait,notify,notifyAll方法详解

控制一些线程去休息或唤醒。必须使用在synchronized代码块中

阻塞阶段

执行wait方法时必须先获得对象的monitor锁。当一个对象调用wait时,本线程会进入阻塞阶段,并释放掉synchronized锁,在阻塞阶段,阻塞阶段只有经历以下四种情况会被唤醒

  • 另一个线程调用这个对象的notify()方法且刚好被唤醒的是本线程;
  • 另一个线程调用这个对象的notifyAll()方法;
  • 过了wait(long timeout)规定的超时时间,如果传入0就是永久等待;
  • 线程自身调用的interrupt()

唤醒阶段

  • notify会唤醒单个阻塞的线程,如果有多个线程在等待,那么会随机选择一个线程进行唤醒
  • notifyAll会将所有等待的线程都唤醒。

遇到中断

如果在阻塞阶段时被中断,则会抛出InterruptException,并释放monitor锁

代码展示

wait用法:
线程1被wait,使用线程2去notify

public class Wait {
    static Object object = new Object();
    public static void main(String[] args) throws InterruptedException {
        Runnable runnable1 = new Runnable() {
            @Override
            public void run() {
                synchronized (object) {
                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("1111111");
                }
            }
        };
        Runnable runnable2 = new Runnable() {
            @Override
            public void run() {
                synchronized (object){
                    object.notify();
                    System.out.println("222222");
                }
            }
        };
        Thread thread1 = new Thread(runnable1);
        Thread thread2 = new Thread(runnable2);
        thread1.start();
        Thread.sleep(100);
        thread2.start();
    }
}

notify与notifyAll:

public class Wait {
    static Object object = new Object();
    public static void main(String[] args) throws InterruptedException {
        Runnable runnable1 = new Runnable() {
            @Override
            public void run() {
                synchronized (object) {
                    try {
                        System.out.println(Thread.currentThread().getName()+"获得Object锁");
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"获得Object锁");
                }
            }
        };
        Runnable runnable2 = new Runnable() {
            @Override
            public void run() {
                synchronized (object){
                  //此时线程1和线程2均能被唤醒
                  //若改为notify,则只有某一个可以被唤醒
                    object.notifyAll();
                    System.out.println(Thread.currentThread().getName()+"调用notify");
                }

            }
        };
        Thread thread1 = new Thread(runnable1);
        Thread thread2 = new Thread(runnable1);
        Thread thread3 = new Thread(runnable2);
        thread1.start();
        thread2.start();
        Thread.sleep(100);
        thread3.start();
    }
}

只释放当前对象monitor

public class Wait {
    static Object lockA = new Object();
    static Object lockB = new Object();
    public static void main(String[] args) throws InterruptedException {
        Runnable runnable1 = new Runnable() {
            @Override
            public void run() {
                synchronized (lockA) {
                    System.out.println("线程A获得A锁");
                    synchronized (lockB){
                        System.out.println("线程A获得B锁");
                        try {
                            lockA.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };
        Runnable runnable2 = new Runnable() {
            @Override
            public void run() {
                synchronized (lockA) {
                    System.out.println("线程B获得A锁");
                    synchronized (lockB){
                        System.out.println("线程B获得B锁");
                    }
                }

            }
        };
        Thread thread1 = new Thread(runnable1);
        Thread thread3 = new Thread(runnable2);
        thread1.start();
        Thread.sleep(100);
        thread3.start();
    }
}

wait,notify,notifyAll特点与性质

  • 必须首先获取到monitor
  • notify只能唤醒其中一个线程
  • 三个方法均属于Object类,被native修饰
  • 相对底层,功能类似JDK帮我们封装Condition。

wait原理

在这里插入图片描述
线程start前处于状态1,start后数据状态2,开始争抢锁,在争抢到锁后有两种选择,一种为6,一种为3,6为正常运行结束,3为调用wait()方法,进入等待,当调用notify方法后,线程进入状态5,该状态与状态2相同,均为争抢锁状态。

使用wait和notify来实现生产者消费者模式

生产者消费者模式简介

在这里插入图片描述

生产者和消费者模式是一种并发设计模式,生产者消费者模式解决的是两者速率不一致而产生的阻抗不匹配,该模式通过平衡生产线程和消费线程的工作能力来提高程序的整体处理数据的速度。
生产者消费者模式是通过一个容器来解决生产者和消费者的强耦合问题。生产者和消费者彼此之间不直接通讯,而通过阻塞队列来进行通讯,所以生产者生产完数据之后不用等待消费者处理,直接扔给阻塞队列,消费者不找生产者要数据,而是直接从阻塞队列里取,阻塞队列就相当于一个缓冲区,平衡了生产者和消费者的处理能力。

代码实现(使用wait和notify实现生产者消费者模式)

public class ProducerConsumerModel {
    static Storage storage = new Storage();
    public static void main(String[] args) {
        Runnable runnable1 = new Runnable() {
            @Override
            public void run() {
                try {
                    for(int i = 0; i < 100; i++){
                        storage.put();
                        Thread.sleep(10);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Runnable runnable2 = new Runnable() {
            @Override
            public void run() {
                try {
                    for(int i = 0; i < 100; i++){
                        storage.take();
                        Thread.sleep(100);
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread1 = new Thread(runnable1);
        Thread thread2 = new Thread(runnable2);
        thread1.start();
        thread2.start();
    }
}
class Storage{
    private int maxSize;
    private LinkedList<Integer> linkedList;
    private int num ;
    public Storage(){
        maxSize = 10;
        linkedList = new LinkedList<>();
        num = 0;
    }
    public synchronized void put() throws InterruptedException {
        while(linkedList.size() == maxSize){
            wait();
        }
        linkedList.add(num++);
        System.out.println("生产者生产了"+linkedList.size()+"产品");
        notify();
    }
    public synchronized void take() throws InterruptedException {
        while(linkedList.size() == 0){
            wait();
        }
        int t = linkedList.poll();
        System.out.println("消费者消费了"+linkedList.size()+"个产品");
        notify();
    }
}

常见面试问题

  • 用两个线程交替打印0-100的奇偶数

一共有两种实现思路,第一种为使用synchronized锁,第二种为使用wait/notify

public class OneZero {
    static int num = 0;
    static Object lock = new Object();
    public static void main(String[] args){
        Runnable runnable1 = new Runnable() {
            @Override
            public void run() {
                while(num <= 100){
                    synchronized (lock){
                        if((num & 1) == 0){
                            System.out.println(Thread.currentThread().getName()+":"+num++);
                        }
                    }
                }

            }
        };
        Runnable runnable2 = new Runnable() {
            @Override
            public void run() {
                while(num <= 100){
                    synchronized (lock){
                        if((num & 1) != 0){
                            System.out.println(Thread.currentThread().getName()+":"+num++);
                        }
                    }
                }

            }
        };
        Thread thread1 = new Thread(runnable1,"偶数");
        Thread thread2 = new Thread(runnable2,"奇数");
        thread1.start();
        thread2.start();
    }
}

第二种方法

public class OneZero {
    static int num = 0;
    static Object lock = new Object();
    public static void main(String[] args){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                synchronized (lock){
                    while(num <= 100){
                        System.out.println(Thread.currentThread().getName()+":"+num++);
                        try {
                            lock.notify();
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    lock.notify();
                }
            }
        };
        Thread thread = new Thread(runnable);
        Thread thread1 = new Thread(runnable);
        thread.start();
        thread1.start();
    }
}

第二种方法比第一种方法节省更多争抢锁的时间。

手写生产者消费者设计模式

为什么wait需要在同步代码块内使用,而sleep()不需要

如果不在同步代码块中,会导致永久等待,发生线程错误

为什么线程通信的方法wait(),notify()和notifyAll()被定义在Object类里,而sleep定义在Thread类里面?

这三个方法锁级别的操作,锁是绑定在对象中,而不是线程中,经常会有一种情况某个线程持有多个锁。如果将wait(),notify(),notifyAll(),定义在线程中,则很不灵活。

wait方法是属于Object对象的,那调用Thread.wait会怎么样

Thread类在最后会调用notifyAll方法。不建议使用Thread类作为锁对象

notifyAll之后所有线程都会在抢夺锁,如果某线程抢夺失败怎么办。

等待锁的持有者释放

suspend和resume来阻塞线程可以吗,为什么?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值