java 计时线程_Java计时器的多个线程

在您的代码中,您使用类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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值