Java Object的wait()、notify、notifyAll()

wait()、notify、notifyAll()必须在同步代码块中,而且是对象锁,对象锁的对象是wait()、notify、notifyAll()的对象。否则报java.lang.IllegalMonitorStateException。

wait()会释放锁,阻塞当前线程,当前线程进入等待队列。
notify会唤醒等待队列中的一个线程,进入同步队列。唤醒哪一个线程由操作系统的多线程管理决定。
notifyAll()会唤醒等待队列中所有线程,进入同步队列。

同步队列中的线程进行非公平竞争获得锁。

公平竞争:先进入队列先获得锁的竞争。

wait()所在线程interrupt()后会抛出InterruptedException,执行线程复位:当前线程被标记为非被中断(当前线程isInterrupted()为false),当前线程被唤醒。

/**
 * @Author: ZhangHao
 * @Description: wait()测试
 * @Date: 2020/9/10 14:29
 * @Version: 1.0
 */
public class Test1 {
    public static void main(String[] args) {
        Object obj=new Object();

        Thread thread = new Thread(() -> {
            synchronized (obj){
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("no waiting");
                System.out.println(Thread.currentThread().isInterrupted());
            }
        }, "thread1");
        thread.start();

        thread.interrupt();
    }
}
java.lang.InterruptedException
	at java.lang.Object.wait(Native Method)
	at java.lang.Object.wait(Object.java:502)
	at org.example.Test1.lambda$main$0(Test1.java:18)
	at java.lang.Thread.run(Thread.java:745)
no waiting
false

猜你喜欢

转载自blog.csdn.net/haoranhaoshi/article/details/108528340