我有一个Runnable“NanoClock
”类不断更新其run()
方法私人挥发性双重价值。的Java:volatile变量不更新(get和set方法不工作)
这个类也具有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方法中将运行设置为true,所以你的while循环将永远不会停止... – home
你认为'new NanoClock()'做了什么? –
@home但运行方法只调用一次,对吧?所以它应该将运行转化为true,然后停留在while循环中,直到我将运行的值更改为false,这会导致完成方法并结束线程...或者运行方法是由它自己连续调用的吗? @SotiriosDelimanolis我想'新的NanoClock()'调用类的构造函数并创建objet的实例,然后我可以转换为一个线程。我已经多次见过这种做法......它有什么问题吗? – AlpayY