1 线程等待与通知
- 等待wait()
线程挂起,释放当前持有资源的锁。 - 通知noitfy()
线程恢复,继续执行。
2 样例
package thread;
import java.util.logging.Logger;
/**
* Wait, Notify测试.
*
* @author xindaqi
* @since 2021/4/16 17:28
*/
public class ThreadWaitNotifyTest {
private static final Logger logger = Logger.getLogger("ThreadWaitNotifyTest");
private final Object flag = new Object();
class ThreadA extends Thread {
@Override
public void run() {
synchronized (flag) {
for (int i = 1; i <= 4; i += 2) {
flag.notify();
logger.info("奇数:" + i);
}
try {
logger.info("进入ThreadA wait");
flag.wait();
logger.info("重新进入ThreadA");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
class ThreadB extends Thread {
@Override
public void run() {
synchronized (flag) {
for (int i = 2; i <= 4; i += 2) {
flag.notify();
logger.info("偶数:" + i);
if (i == 4) {
logger.info("退出当前线程");
Thread.currentThread().interrupt();
}
}
try {
logger.info("进入ThreadB wait");
flag.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
public static void main(String[] args) {
ThreadWaitNotifyTest threadWaitNotifyTest = new ThreadWaitNotifyTest();
ThreadA threadA = threadWaitNotifyTest.new ThreadA();
threadA.start();
ThreadB threadB = threadWaitNotifyTest.new ThreadB();
threadB.start();
}
}
3 结果
四月 16, 2021 6:24:40 下午 thread.ThreadWaitNotifyTest$ThreadA run
信息: 奇数:1
四月 16, 2021 6:24:40 下午 thread.ThreadWaitNotifyTest$ThreadA run
信息: 奇数:3
四月 16, 2021 6:24:40 下午 thread.ThreadWaitNotifyTest$ThreadA run
信息: 进入ThreadA wait
四月 16, 2021 6:24:40 下午 thread.ThreadWaitNotifyTest$ThreadB run
信息: 偶数:2
四月 16, 2021 6:24:40 下午 thread.ThreadWaitNotifyTest$ThreadB run
信息: 偶数:4
四月 16, 2021 6:24:40 下午 thread.ThreadWaitNotifyTest$ThreadB run
信息: 退出当前线程
四月 16, 2021 6:24:40 下午 thread.ThreadWaitNotifyTest$ThreadB run
信息: 进入ThreadB wait
四月 16, 2021 6:24:40 下午 thread.ThreadWaitNotifyTest$ThreadA run
信息: 重新进入ThreadA
Process finished with exit code 0
【参考文献】
[1]https://segmentfault.com/a/1190000018096174?utm_source=tag-newest
[2]https://www.cnblogs.com/sxdcgaq8080/p/6214853.html
[3]https://blog.csdn.net/qq_38215702/article/details/89743601