您的位置:首页 > 移动开发 > Objective-C

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方法能将当前线程进入等待池。

在锁池里的线程才有资格争夺锁。
所以notify可能会导致死锁,而notify不会。

posted @ 2019-05-28 17:22 jarjune 阅读(...) 评论(...) 编辑 收藏
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: