public class Main {
private static int sec = 5;
public static void main(String[] args) {
Teacher teacher = new Teacher();
new Thread(() -> {
synchronized (teacher) {
System.out.println("老师等待铃响...");
try {
teacher.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
teacher.teach();
System.out.println("学生: 老师好");
}
}).start();
new Thread(() -> {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (teacher) {
if (--sec == 0) {
System.out.println("上课了 通知老师上课");
teacher.notify();
break;
} else {
System.out.println("还有" + sec + "秒上课");
}
}
}
}).start();
}
static class Teacher {
public void teach() {
System.out.println("老师: 上课!");
}
}
}
Java 对象的wait和notify方法
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 简书:capo 转载请注明原创出处,谢谢! 前言: 今天,我们讲讲Object中wait和notify/not...