Object中wait()、notify()、notifyAll()
2019-05-28 17:22
253 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42054277/article/details/90705574
Object中wait()、notify()、notifyAll()
解释
必须在
synchronized修饰的方法/代码块中使用。
wait()
将当前线程持有对象的锁交出(允许其他线程持有),并进入等待状态。
notify()
唤醒某一个正在等待的线程(由某一个正在等待的线程获取锁)。
notifyAll()
通知所有正在等待的线程(所有正在等待的线程争夺一个锁),由jvm决定唤醒哪一个。
例子
并不是立即唤醒,而是等待被
synchronized修饰的代码执行完,释放锁之后才执行,具体看下面demo
public class TestObject {
public static Object o = new Object();
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new MyThread1();
Thread thread2 = new MyThread2();
thread1.start();
Thread.sleep(2000);
thread2.start();
}
static class MyThread1 extends Thread {
@Override
public void run() {
System.out.println("1 >>>> 输出A1");
synchronized (o) {
System.out.println("2 >>>> 输出A2");
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("6 >>>> 输出A3");
}
System.out.println("7 >>>> 输出A4");
}
}
static class MyThread2 extends Thread {
@Override
public void run() {
System.out.println("3 >>>> 输出B1");
synchronized (o) {
System.out.println("4 >>>> 输出B2");
o.notify();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("5 >>>> 输出B3");
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("8 >>>> 输出B4");
}
}
}
[/code]
输出结果
1 >>>> 输出A1
2 >>>> 输出A2
3 >>>> 输出B1
4 >>>> 输出B2
5 >>>> 输出B3
6 >>>> 输出A3
7 >>>> 输出A4
8 >>>> 输出B4
思考?同样是唤醒一个线程,notify()与notifyAll()有什么区别?
这个时候就要说到锁池和等待池了。
- 锁池:通过notify方法能将等待该对象的某一个线程进入锁池,而notityAll方法能将等待该对象的所有线程都进入锁池。
- 等待池:通过调用wait方法能将当前线程进入等待池。
posted @ 2019-05-28 17:22 jarjune 阅读(...) 评论(...) 编辑 收藏在锁池里的线程才有资格争夺锁。
所以notify可能会导致死锁,而notify不会。
相关文章推荐
- Thread的join()方法和Object的wait(),notify(),notifyAll()方法
- 使用Object的wait,notify,notifyAll做线程调度
- 【Java基础之Object类(二)、线程同步(一)】Java中使用Object类的wait,notify,notifyAll做线程调度
- Java中的synchronized、Object.wait()、Object.notify()/notifyAll()原理
- java Object 对象的的wait()、notify()、notifyAll()介绍
- Java_Object_wait()、notify()、notifyAll()
- Object的notify,wait,notifyAll
- wait()和notify(),notifyAll()是Object类的方法,sleep()和yield()是Thread类的方法
- Java中的synchronized、Object.wait()、Object.notify()/notifyAll()原理
- Object中的wait,notify,notifyAll基本使用
- java线程同步:使用Object的wait,notify,notifyAll做线程调度
- Java中的synchronized、Object.wait()、Object.notify()/notifyAll()原理
- 有关Object之wait(),notify() 和notifyAll() 以及Thread之sleep(),join()和yield()
- 多线程开发之Object.wait() notify() notifyall()
- Object的wait、notify、notifyall方法解析
- JAVA源码剖析之---Object类(三)---toString,wait,notify,notifyAll,finalize方法的使用
- 【Java并发系列02】Object的wait()、notify()、notifyAll()方法使用
- Java_Object_wait()、notify()、notifyAll()
- java Object 类中 notify() ,notifyAll() ,wait()
- Java中的synchronized、Object.wait()、Object.notify()/notifyAll()的使用