import java.util.concurrent.TimeUnit;
/**
* User: ldj
* Date: 2023/4/29
* Time: 12:47
* Description: No Description
*/
public class WaitAndSleep {
public static void main(String[] args) {
// 注意:wait(),notify(),notifyAll()只能使用在同步代码块或者同步方法中.
new Thread(() -> {
synchronized (WaitAndSleep.class) {
System.out.println("线程1开始:[" + Thread.currentThread().getName() + "]");
System.out.println("线程1进入等待状态");
try {
WaitAndSleep.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1被通知");
System.out.println("线程1结束");
}
}, "thread1").start();
new Thread(() -> {
synchronized (WaitAndSleep.class) {
System.out.println("线程2开始:[" + Thread.currentThread().getName() + "]");
//唤醒等待池中的线程1的 WaitAndSleep.class对象
WaitAndSleep.class.notifyAll();
System.out.println("线程2进入睡眠状态");
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程2睡醒了");
System.out.println("线程2结束");
}
}, "thread2").start();
}
}
//线程1开始:[thread1]
//线程1进入等待状态
//线程2开始:[thread2]
//线程2进入睡眠状态
//线程2睡醒了
//线程2结束
//线程1被通知
//线程1结束
wait和sleep方法的区别
于 2023-04-29 13:40:17 首次发布