// 示例代码:使用 sleep 方法
public class SleepExample {
public static void main(String[] args) {
try {
System.out.println("开始睡眠...");
// 让当前线程暂停 2 秒钟
Thread.sleep(2000);
System.out.println("睡眠结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 解释说明:
// Thread.sleep(long millis) 方法会让当前正在执行的线程暂停指定的时间(以毫秒为单位)。
// 在这段时间内,线程不会占用 CPU 资源。该方法通常用于让程序在某些情况下暂停执行一段时间。
// 示例代码:使用 wait 方法
public class WaitExample {
public static void main(String[] args) {
final Object lock = new Object();
Thread t1 = new Thread(() -> {
synchronized (lock) {
try {
System.out.println("线程 " + Thread.currentThread().getName() + " 等待...");
// 让当前线程等待,直到其他线程调用 notify 或 notifyAll 方法
lock.wait();
System.out.println("线程 " + Thread.currentThread().getName() + " 继续执行");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(() -> {
synchronized (lock) {
System.out.println("线程 " + Thread.currentThread().getName() + " 唤醒其他线程...");
// 唤醒一个或所有等待的线程
lock.notifyAll();
}
});
t1.start();
// 让 t1 先启动并进入等待状态
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
}
// 解释说明:
// Object.wait() 方法会让当前线程等待,直到其他线程调用同一个对象上的 notify() 或 notifyAll() 方法。
// wait() 方法必须在同步代码块中调用,并且会释放当前对象的锁。
// notify() 和 notifyAll() 方法用于唤醒一个或所有等待的线程。
上一篇:java图片压缩
下一篇:javajdbc连接数据库
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站