Please look at this code(taken from Effective Java book)
import java.util.concurrent.TimeUnit;
public class Main {
private static boolean stopReq;
public static void main(String[] args) throws InterruptedException {
Thread bgw = new Thread(new Runnable()
{
public void run(){
int i = 0;
while(!stopReq){ i++;}
}
});
bgw.start();
TimeUnit.SECONDS.sleep(1);
stopReq = true;
}
}
Why does the bgw
thread get stuck in an infinite loop? Is it caching it's own copy of stopReq
when it reached the loop? So it never sees the updated value from the other thread?
I understand the solution to this problem would be synchronizing or a volatile variable, but I am curious to why this current implementation doesn't work.
thanks
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…