【Java】多线程-wait/notify

1、wait和notify

Java的多线程中,线程的执行顺序和时间都是不定的。为了控制线程的调度顺序,前面我们引入了join()方法。

但是join()只能在线程执行完后,才能执行其他线程,有没有什么方法可以在线程执行顺序中来调度其他线程呢?

这里我们引入了wait()和notify()方法

wait()、notify()和notifyAll()都是属于Object类中的方法,任何对象都可以调用这几个方法

wait()/wait(time):让当前进程进入阻塞状态

notify()/notifyAll():唤醒当前对象上等待的对象

wait()的基本用法是

Object object = new Object();
synchronized (object){
   try {
       object.wait();
   } catch (InterruptedException e) {
       throw new RuntimeException(e);
   }
       

notify()基本用法

synchronized (object){
      object.notify();
} 

2、注意事项

(1)wait()和notify()在使用时都要加锁

在使用上述三个方法时,需要对竞争资源进行加锁,不然就会报错

并且wait()方法在使用时,线程必须获得锁对象的控制权

(2)阻塞状态

线程调用wait()方法后,线程进入阻塞状态(WAITING

阻塞状态什么也不做,不会占用CPU

 

(3) notify的调用位置

对象调用wait方法后,对象锁被释放,这时必须由其他线程来唤醒对象

如果将notify写在同一线程中,则不能唤醒当前对象

public class demo {
    public static void main(String[] args) {
        Object object = new Object();
        System.out.println("开始进程");
        synchronized (object){
            try {
                object.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            object.notify();
        }
        System.out.println("结束进程");
    }
}

线程会继续阻塞 

3、wait()带参数方法和notifyAll()

 (1)wait()带参数方法

 wait(long timeout)中的参数表示线程阻塞的超时时间,如果超过这个时长,那么线程会被自动唤醒

避免无休止地等待下去

public class demo {
    public static void main(String[] args) {
        Object object = new Object();
        Thread thread1 = new Thread(()->{
            synchronized (object){
                System.out.println("线程1开始执行");
                try {
                    object.wait(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("线程1执行结束");
            }
        });

        Thread thread2 = new Thread(()->{
            System.out.println("线程2开始执行");
            System.out.println("线程2执行结束");
        });

        thread1.start();
        thread2.start();

    }
}

上述代码中,并没有对线程1进行唤醒操作,而是在1000ms的等待时间结束后,线程1自动唤醒,打印结果并结束线程 

(2)notifyAll() 

notify()一次唤醒一个线程,notifyAll() 一次唤醒全部线程

由于唤醒线程的过程中也要进行锁的竞争,因此notifyAll()的唤醒并不是并行执行,而是串行执行的

 · 多次notify()唤醒多个线程

public class demo {
    public static void main(String[] args) {
        Object object = new Object();

        Thread thread1 = new Thread(()->{
            synchronized (object){
                System.out.println("线程1开始执行");
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("线程1拿回锁");
                System.out.println("线程1执行完毕");
            }
        });

        Thread thread2 = new Thread(()->{
            synchronized (object){
                System.out.println("线程2开始执行");
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("线程2拿回锁");
                System.out.println("线程2执行完毕");
            }
        });

        Thread thread3 = new Thread(()->{
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            synchronized (object){
                System.out.println("线程3开始执行");
                object.notify();
                object.notify();
                System.out.println("线程释放锁");
                System.out.println("线程3执行完毕");
            }
        });

        thread1.start();
        thread2.start();
        thread3.start();
    }
}

线程3唤醒两次,使得线程1和线程2先后拿回锁

 · notifyAll() 

public class demo {
    public static void main(String[] args) {
        Object object = new Object();

        Thread thread1 = new Thread(()->{
            synchronized (object){
                System.out.println("线程1开始执行");
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("线程1拿回锁");
                System.out.println("线程1执行完毕");
            }
        });

        Thread thread2 = new Thread(()->{
            synchronized (object){
                System.out.println("线程2开始执行");
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("线程2拿回锁");
                System.out.println("线程2执行完毕");
            }
        });

        Thread thread3 = new Thread(()->{
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            synchronized (object){
                System.out.println("线程3开始执行");
                object.notifyAll();
                System.out.println("线程释放锁");
                System.out.println("线程3执行完毕");
            }
        });

        thread1.start();
        thread2.start();
        thread3.start();
    }
}

执行结果

 

3、关于锁释放的时间

在线程2唤醒 线程1后,线程2会立即释放锁吗?

我们通过一段代码来验证一下

public class demo {
    public static void main(String[] args) {
        Object object = new Object();
        Thread thread1 = new Thread(()->{
            synchronized (object){
                System.out.println("线程1开始执行");
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("线程1拿回锁");
                System.out.println("线程1执行结束");
            }
        });

        Thread thread2 = new Thread(()->{
            synchronized (object){
                System.out.println("线程2拿到锁");
                System.out.println("线程2开始执行");
                System.out.println("线程2释放锁");
                object.notify();
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("线程2执行结束");
            }
        });

        thread1.start();
        thread2.start();
    }
}

上述代码执行结果为:

可以看到,在线程2调用notify()唤醒线程1后,就算进行了休眠,也并没有释放锁;而是在线程2的代码全部执行完后,线程2才释放锁

所以,我们可以得出的结论是:在一个线程唤醒其他线程后,它不会立即释放锁,而是要在本线程代码执行完后才释放锁 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

沙河板混

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

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

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

打赏作者

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

抵扣说明:

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

余额充值