实例深入理解Java wait/notify执行机制

来源:互联网 发布:剑网3成男捏脸数据分享 编辑:程序博客网 时间:2024/05/17 22:37

Java wait/notify

wait 使得获取到同步锁的线程在调用wait方法的时候暂停执行,让出cpu的时间片
notify 通知获取同步锁的线程在获取到cpu的时间片后继续执行
代码案例分析:
public class MyClass {

public static void main(String[] args) {    //同步对象    Object lock = new Object();    Thread1 thread1 = new Thread1(lock);    thread1.setName("Thread1");    thread1.start();    //执行sleep()方式,尝试让thread1执行完毕,但是thread1在调用wait方式后就会暂停执行    try {        Thread.sleep(3000);    } catch (InterruptedException e) {        e.printStackTrace();    }    //启动执行notify的线程,让执行notify操作    Thread2 thread2 = new Thread2(lock);    thread2.setName("Thread2");    thread2.start();}

}
class Thread1 extends Thread {

private Object lock;public Thread1(Object lock) {    super();    this.lock = lock;}@Overridepublic void run() {    try {        synchronized (lock) {            System.out.println("wait start== " + System.currentTimeMillis());            lock.wait();//当前线程暂停执行,等待其他现在执行notify或者notifyall操作,然后继续执行。            System.out.println("wait end== " + System.currentTimeMillis());        }    } catch (InterruptedException e) {        e.printStackTrace();    }}

}

class Thread2 extends Thread {

private Object lock;public Thread2(Object lock) {    super();    this.lock = lock;}@Overridepublic void run() {    synchronized (lock) {        System.out.println("notify start== " + System.currentTimeMillis());        //执行notify操作让处于wait的线程,继续执行后面的逻辑。        lock.notify();        System.out.println("notify end== " + System.currentTimeMillis());    }}

}

执行结果:
wait start== 1469078090375——–Thread1 执行run方法到lock.wait()的时候,就暂停了
notify start== 1469078093376——–Thread2 执行run方法到lock.wait()的时候,就暂停了
notify end== 1469078093376——–Thread2继续执行
wait end== 1469078093376——–Thread1收到Thread2的notify通知,然后继续执行下面的代码,结束线程

1 0