多线程
wait()使一个线程中断执行,处于等待的状态,
notify()则是唤醒一个处于等待的线程,继续向下执行
上简单案例
同时思考几个问题
package com.zmkj.admin.test;
/**
* wait() notify() 简单案例
*
* 知识点:
* 1、线程的等待、睡眠、唤醒 方式
* 2、notify 是立即释放锁吗?
*
* @author sunminghao
*/
public class WaitAndNotify {
final static Object object = new Object();
public static class T1 extends Thread{
@Override
public void run(){
synchronized (object){
System.out.println(System.currentTimeMillis() + " :T1 start!");
try {
System.out.println(System.currentTimeMillis() + ": T1 wait for object");
object.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() + ": T1 end!");
}
}
}
public static class T3 extends Thread{
@Override
public void run(){
synchronized (object){
System.out.println(System.currentTimeMillis() + " :T3 start!");
try {
System.out.println(System.currentTimeMillis() + ": T3 wait for object");
object.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() + ": T3 end!");
}
}
}
public static class T2 extends Thread{
@Override
public void run(){
synchronized (object){
System.out.println(System.currentTimeMillis() + " :T2 start! notify one thread");
object.notify();
//这里有个问题 那就是 notify 是有序唤醒呢 还是随机唤醒呢 ?
//你猜 瞎猜 有序?随机?
//唤醒全部
// object.notifyAll();
System.out.println(System.currentTimeMillis() + ": T2 end!");
try {
System.out.println(System.currentTimeMillis() + ": T2 sleep start!");
Thread.sleep(2000);
System.out.println(System.currentTimeMillis() + ": T2 sleep end!");
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Thread t1 = new T1();
Thread t3 = new T3();
Thread t2 = new T2();
t3.start();
t1.start();
t2.start();
}
}
例子中 我们创建了 t1 和 t3 是执行wait()的方法,
t2 在执行notify()方法时候 只是唤醒了一个 这个时候我们可以看到 系统并没终止执行。是因为 t3 还处于等待的状态
t2 在执行notifyAll()方法时候 是唤醒了所有在等待的线程 ,处于等待的 t1 和 t3 都会再次执行 最后系统执行完自动终止
那就有个疑惑了
1、notify 在唤醒线程的时候 会立即释放锁吗?
其实上面的样例已经解释了这个问题。
在 t2 执行完notify 方法时,我们将其sleep了一段时间。这个时候 t1 或者 t3 并没有执行,而是等t2 方法结束了才开始执行的。
可见notify 并不是直接释放锁的
**
2、notify 是如何唤醒的等待的线程的呢?是随机唤醒?还是有序唤醒?
**
网上有很多都解释为随机唤醒的
简单的来看也没毛病 毕竟notify方法并未具体指定唤醒哪一个啊
哈哈。其实是有序的!!!!
下面将用另外一个样例解释这个问题
https://blog.csdn.net/qq_34129814/article/details/117222743