在您的代码中,您使用类T2和T3来打印7秒和15秒消息,但是没有标识哪个消息和它们实际上是相同的,保存了名称和要打印的字符串.调用notify()时,没有给出锁定的可指定顺序.从Javadocs中的notify():
The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object
因此,获取getSharedTime()锁定的方法(T2的run()或T3的run())将继续并打印.有关更多信息,请参见this question和Javadocs.
这是执行相同操作的类似方法,我将检查时间是否为7或15的倍数移到了它们各自的类上,并以不同的方式构造了wait()和notify().我还将打印与Timer类同步,以便同时(有效)通知所有wait().在Timer类中处理每秒的打印时间,现在,它的设置方式将提供您指定的输出,但是将打印和调用setTime以及将时间初始化为0时,将输出更准确的输出到当前时间.
class Timer extends Thread{
private int time = 1;
private boolean setting = false;
public void run(){
while(true){
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(time + " ");
setTime(time + 1);
//Switching the order of these 2 ^^^ statements and initializing time to 0 will give an output that is more accurate to the time.
}
}
public synchronized int getTime(){
while(setting){
try {
wait(); //This will only be run on the off-chance that setTime is being run at the same time.
} catch (InterruptedException e) { }
}
return time;
}
public synchronized void setTime(int t){
setting = true;
this.time = t;
setting = false;
notifyAll();
}
}
class Timer7 extends Thread{
Timer timer;
public Timer7(Timer t){
this.timer = t;
}
public void run(){
synchronized(timer){
while(true){
try {
timer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(timer.getTime() % 7 == 0){
System.out.print("
7 Second Message
");
}
}
}
}
}
class Timer15 extends Thread{
Timer timer;
public Timer15(Timer t){
this.timer = t;
}
public void run(){
synchronized(timer){
while(true){
try {
timer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(timer.getTime() % 15 == 0){
System.out.print("
15 Second Message
");
}
}
}
}
}
public class Main2 {
public static synchronized void main(String[] args) {
Timer timer = new Timer();
timer.start();
Timer7 t7 = new Timer7(timer);
t7.start();
Timer15 t15 = new Timer15(timer);
t15.start();
}
}