// sleep 示例
public class SleepExample {
public static void main(String[] args) {
try {
System.out.println("Sleeping for 2 seconds...");
// sleep 方法让当前线程暂停执行指定的时间(毫秒),并进入休眠状态。
// 在这段时间内,线程不会释放任何监视器(锁)。
Thread.sleep(2000);
System.out.println("Woke up!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// wait 示例
public class WaitExample {
public static void main(String[] args) {
final Object lock = new Object();
new Thread(() -> {
synchronized (lock) {
try {
System.out.println("Waiting for another thread to notify...");
// wait 方法让当前线程暂停执行,并释放它所持有的锁。
// 只能在同步代码块或方法中调用 wait。
lock.wait();
System.out.println("Notified, continuing execution.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
try {
Thread.sleep(2000); // 让第二个线程等待2秒后通知第一个线程
synchronized (lock) {
System.out.println("Notifying the waiting thread...");
lock.notify(); // 唤醒一个在该对象上等待的线程
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
sleep
方法:
Thread.sleep(long millis)
是静态方法,作用是让当前正在执行的线程暂停执行指定的时间(以毫秒为单位),在这段时间内,线程不会释放任何监视器(锁)。sleep
。wait
方法:
Object.wait()
是实例方法,必须在同步代码块或同步方法中调用。它会让当前线程暂停执行,并释放它所持有的锁。wait
和 notify/notifyAll
搭配使用。上一篇:java生成唯一id
下一篇:java数组遍历
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站