Creating a fake clock whose data can be accessed from another thread

时间:2016-04-25 09:07:39

标签: java

I want to build an extension of TimerTask that runs in a continual loop (ie. as a fake clock), but I need the 'time' to be accessible from other methods.

I've managed to get the clock going so it runs fine, and will print back the 'correct' time to the console from within the clock loop. But whenever I try to access the hours/days/years on the fake clock from a different method, it prints back the original initialization value of 0 days, 0 months, 0 years...even when the clock itself is further along as seen in the console view, ie. 5 days, 6 months, 9 years.

My TimerTask increments as below (but for all of hour, day, month, year): if (currenthour == 24) { currenthour = 0; currentday++; } At the end of the loop, I'm putting the thread to sleep for 1000 ms to slow it down.

I suspect this has to do with thread locks? But can't seem to find a way to prove/disprove that theory, or to fix the problem. Any help would be greatly appreciated!

1 个答案:

答案 0 :(得分:1)

我发现了错误,这与线程无关。我创建了另一个正在读取的对象的实例化。

相关问题