1.最近在学习Java多线程,看到视频中要实现一个类似闹钟和小明的情景, 要求闹钟响,小明关闹钟, 三秒后闹钟再响,小明再关, 重复10次程序结束. 不知道为什么我的程序小明只能输出一次.
public class Test {
public static void main(String[] args) {
Clock ck = new Clock();
new XiaoMing(ck);
}
}
public class Clock implements Runnable{
public Boolean isAlarm;
public Boolean shutdown;
public Clock() {
isAlarm = false;
shutdown = false;
new Thread(this).start();
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
isAlarm = true;
System.out.println("Get up * 3 !");
synchronized (this) {
notifyAll();
try {
wait(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
shutdown = true;
}
}
public class XiaoMing implements Runnable{
private Clock clk;
public XiaoMing(Clock clk) {
this.clk = clk;
new Thread(this).start();
}
@Override
public void run() {
while(true) {
if (clk.isAlarm) {
System.out.println("Woshixiaoming!");
clk.isAlarm = false;
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
else{
if(clk.shutdown) break;
}
}
}
}
输出结果如下
Get up * 3 !
Woshixiaoming!
Get up * 3 !
Get up * 3 !
...(10 次 Getup, 之后程序停在那里)
一只斗牛犬
相关分类