Victor is right, there are issues with your code: atomicity and visibility.
Here's my edition:
private int count;
private volatile boolean stop;
private volatile boolean stopped;
@Override
public void run() {
while (!stop) {
count++; // the work
}
stopped = true;
System.out.println("Count 1 = " + count);
}
public void stopCounting() {
stop = true;
while(!stopped)
; //busy wait; ok in this example
}
public int getCount() {
if (!stopped) {
throw new IllegalStateException("not stopped yet.");
}
return count;
}
}
If a thread observes that stopped==true
, it's guaranteed that the work completes and the result is visible.
There is a happens-before relation from volatile write to volatile read (on the same variable), so if there are two threads
thread 1 thread 2
action A
|
volatile write
volatile read
|
action B
action A happens-before action B; writes in A are visible by B.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…