【发布时间】:2017-07-09 08:14:04
【问题描述】:
我有一个 Runnable "NanoClock" 类,它在其 run() 方法中不断更新私有 volatile double 值。
这个类还有一个getTime() 方法,它返回双精度值。另一个类(“Master”)正在构造NanoClock 类并创建一个线程,同时调用start() 方法。
执行此操作后,它会多次调用getTime() 方法(有延迟),但值没有更新。我做错了什么?
NanoClock.java:
public class NanoClock implements Runnable {
private volatile boolean running;
private volatile double time;
public NanoClock() {
time = System.currentTimeMillis();
}
@Override
public void run() {
running = true;
while(running) {
try {
if(System.currentTimeMillis() > time) {
time = System.currentTimeMillis();
}
//This returns the updated value continuously when commented out
//System.out.println("Time: " + String.format("%.6f", unix_time));
Thread.sleep(2000);
} catch(Exception exc) {
exc.printStackTrace();
System.exit(1);
}
}
}
public double getTime() {
return time;
}
public void end() {
running = false;
}
}
Master.java:
public class Master {
public static void main(String[] args) {
try {
NanoClock nClock = new NanoClock();
Thread clockThread = new Thread(new NanoClock());
clockThread.setPriority(10);
clockThread.start();
//MY_ISSUE: This returns the same value every time
for(int a = 0; a < 10; a++) {
System.out.println("Time: " + nClock.getTime());
}
//MY_ISSUE: This cannot stop the while loop - I tested it with
//the println in the NanoClock class.
nClock.end();
System.out.println("Done!");
catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
【问题讨论】:
-
你总是在 run 方法中将 running 设置为 true,所以你的 while 循环永远不会停止......
-
你认为
new NanoClock()会做什么? -
@home 但是 run 方法只被调用一次,对吧?所以它应该将running变为true,然后停留在while循环中,直到我将running的值更改为false,这导致完成方法并结束线程......还是run方法本身被连续调用? @SotiriosDelimanolis 我认为
new NanoClock()调用类构造函数并创建对象的实例,然后我可以将其转换为线程。这种做法我已经看过好几次了……有什么问题吗? -
@AlpayY:你当然是对的。我没有正确阅读整个代码...
标签: java multithreading synchronization shared-memory volatile