Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

multithreading - Why does Java not see the updated value from another thread?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your explanation is right.

The compiler detects than stopReq is never modified in the loop and since it is not volatile, optimizes the while(!stopReq) instruction to while(true).

Even though the value changes later, the thread does not even read it any more.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...