一、wait、notify
wait、notify 是java 根级父类Obeject 中定义得两个方法,其相关作用如下:
object.wait():执行该语句,会让获取了该object对象锁得线程进入WAIT状态,并释放该object对象锁;
object.notify():执行该语句,会唤醒此object对象监视器上等待的单个线程,但是并不会释放锁,而是会继续执行剩余语句,直到执行完synchronized块,才会释放object对象锁;
object.notifAll():同上,但是会唤醒此对象监视器上等待的所有线程;
二、代码实践
WaitThread
public class WaitThread extends Thread {
private final Object lock;
public WaitThread(Object lock) {
super();
this.lock = lock;
}
@Override
public void run() {
System.out.println("this is wait");
try {
synchronized (lock) {
long start = System.currentTimeMillis();
System.out.println("开始 wait time= " + start);
lock.wait();
long end = System.currentTimeMillis();
System.out.println("结束 wait time= " + end);
System.out.print("wait time = " + (end - start));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
NotifyThread
public class NotifyThread extends Thread {
private final Object lock;
public NotifyThread(Object lock) {
super();
this.lock = lock;
}
@Override
public void run() {
System.out.println("this is notify");
synchronized (lock) {
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
// 业务逻辑完成了...
System.out.println("开始 notify time= " + System.currentTimeMillis());
lock.notify();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("结束 notify time= " + System.currentTimeMillis());
}
}
}
main
public class Main {
public static void main(String[] args) {
Object lock = new Object();
WaitThread t1 = new WaitThread(lock);
t1.start();
NotifyThread t2 = new NotifyThread(lock);
t2.start();
}
}
执行结果
this is wait
this is notify
开始 wait time= 1713457641122
开始 notify time= 1713457644123
结束 notify time= 1713457654137
结束 wait time= 1713457654137
wait time = 13015
代码逻辑简介
- 1、主线程创建了两个线程WaitThread t1 和 NotifyThread t2 并运行着两个线程;
- 2、线程WaitThread t1先获取lock 同步锁,然后 NotifyThread t2只能等待;
- 3、线程WaitThread t1获取锁之后执行相关代码,直到object.wait(),WaitThread t1进入等待状态,并释放锁;
- 4、锁一释放,NotifyThread t2 就会获取该对象得同步锁,并执行后续代码;
- 5、NotifyThread t2线程执行到object.wait(),该语句可以唤醒因object.wait()而处于WAIT状态得线程WaitThread t1,但是此时锁并没有释放,所以WaitThread t1会继续等待锁;直到NotifyThread t2的synchronized模块执行完成,才会释放锁;此时WaitThread t1会获取锁并继续执行,直到线程执行完毕;
- 相关流程如下图:
三、问题
1、notify()是依据什么唤醒等待线程的,即wait()和notify()之间是通过什么相互关联的?
对象的同步锁,即synchronized锁