wait和notify的线程通信机制

2020-04-28  本文已影响0人  文景大大

一、入门实例

通过wait和notify/notiftAll可以实现多线程之间的通信。

@Slf4j
public class Thread1 implements Runnable {
    private String lock;

    public Thread1(String lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        synchronized (lock) {
            log.info("开始wait:{}", System.currentTimeMillis());
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("结束wait:{}", System.currentTimeMillis());
        }
    }
}
@Slf4j
public class Thread2 implements Runnable {
    private String lock;

    public Thread2(String lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        synchronized (lock) {
            log.info("开始notify:{}", System.currentTimeMillis());
            lock.notify();
            log.info("结束notify:{}", System.currentTimeMillis());
        }
    }
}
@Slf4j
public class Test001 {
    public static void main(String[] args) throws InterruptedException {
        String lock = "lock";
        Thread thread1 = new Thread(new Thread1(lock));
        Thread thread2 = new Thread(new Thread2(lock));
        thread1.start();
        Thread.sleep(3000);
        thread2.start();
    }
}

当thread1启动后,执行wait后,就会释放lock锁,从running状态变为blocked状态;

当thread2启动后,能正常获取到lock锁,因此开始执行,执行notify随机唤醒一个等待lock锁的blocked状态的线程,但是thread2并没有执行完同步代码块,因此还不会释放锁,thread1因此还是处于blocked状态,只有等thread2执行完同步代码块,并释放锁之后,thread1才会回到runnable状态,等待CPU资源再进入running状态。

因此,上述例子的打印结果为:

开始wait:1587888213497
开始notify:1587888216508
结束notify:1587888216508
结束wait:1587888216508

二、使用要点

三、线程状态说明

上一篇下一篇

猜你喜欢

热点阅读