Thread-Wait

实例

package com.example.demo.thread;

public class WaitTest {
    public static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        WaitThread1 waitThread1 = new WaitThread1();
        WaitThread2 waitThread2 = new WaitThread2();
        WaitThread3 waitThread3 = new WaitThread3();
        waitThread1.setName("waitThread1");
        waitThread1.start();
        waitThread2.setName("waitThread2");
        waitThread2.start();
        waitThread3.setName("waitThread2");
        waitThread3.start();
    }

}

class WaitThread1 extends Thread {

    public void run() {
        synchronized (WaitTest.lock) {
            System.out.println("start" + Thread.currentThread().getName());
            try {
                WaitTest.lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("end" + Thread.currentThread().getName());
//            Thread.sleep(2000);
        System.out.println("WaitThread1");
    }
}

class WaitThread2 extends Thread {
    public void run() {
        synchronized (WaitTest.lock) {
            System.out.println("start" + Thread.currentThread().getName());
            try {
                WaitTest.lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("end" + Thread.currentThread().getName());
        System.out.println("WaitThread2");
    }
}

class WaitThread3 extends Thread {
    public void run() {
        synchronized (WaitTest.lock) {
            System.out.println("start" + Thread.currentThread().getName());
//            WaitTest.lock.notify();
//            WaitTest.lock.notify(); // 如果只调用一次notify()那么只有一个线程会继续执行
            WaitTest.lock.notifyAll(); // 所有持有WaitTest.lock的线程都会重新到就绪态
        }

        System.out.println("end" + Thread.currentThread().getName());
        System.out.println("WaitThread3");
    }
}

输出

startwaitThread1
startwaitThread2
startwaitThread2
endwaitThread2
endwaitThread2
WaitThread2
endwaitThread1
WaitThread1
WaitThread3

从输出结果看,wait会释放锁,并等待唤醒,notify()会导致线程重新进入就绪态,notifyAll()会将所有持有当前锁的线程编程就绪态

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值