package demo08;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class WaitAndNotify {
public static void main(String[] args) throws InterruptedException {
String lock = "abc";
ExecutorService es = Executors.newFixedThreadPool(3);
es.submit(new Runnable() {
@Override
public void run() {
synchronized (lock){
System.out.println("线程一睡眠");
try {
lock.wait();
}catch (Exception e){
e.printStackTrace();
}
}
System.out.println("线程一被唤醒继续执行任务");
}
});
Thread.sleep(3000);
es.submit(new Runnable() {
@Override
public void run() {
System.out.println("线程二唤醒线程一");
lock.notify();
System.out.println("线程二执行任务结束");
}
});
}
}
需求:线程一等待,利用线程二唤醒一
问:使用线程池怎么完成需求?
这段代码实现了多线程之间的等待/通知模型,它使用了 wait 和 notify 两个方法。
代码定义了一个简单的字符串对象 lock,然后通过线程池(ExecutorService)创建了两个线程。
第一个线程在同步代码块中运行,并在该代码块内部调用 wait 方法。在第一个线程调用 wait 方法时,它会释放对 lock 的锁定,并在等待通知之前进入睡眠状态。
在等待 3 秒后,程序开启第二个线程,该线程将调用 notify 方法,从而唤醒第一个线程。第一个线程接到通知后,重新获得对 lock 的锁定,并继续执行剩余的任务。
简单地说,第一个线程等待第二个线程的通知,而第二个线程则通知第一个线程继续执行任务。