When does java thread cache refresh happens?

前端 未结 4 999
情歌与酒
情歌与酒 2020-12-15 11:22

Thread 1: is executing this loop

while(running) {
// Do Task()
} 
println(\"Done\");

Thread 2 sets running false In case running is a vol

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 11:39

    Why not try it yourself?

    public class ThreadTest {
    
    private static boolean running = true;
    
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread() {
            public void run() {
                while( running ) {
                    System.out.println( "Running.");
                }
                long l = System.nanoTime();
                System.out.println( "Stopped at "+l);
    
            }
        };
        t.start();
        Thread.sleep( 1 );
        running = false;
        long l = System.nanoTime();
        System.out.println( "Stopping at "+l);
    }
    }
    

    It's by no means a perfect test but it gives you a rough estimate. On my machine the difference was approx 25ms. Of course it has to execute the System.out.println too, but that certainly doesn't take that long.

提交回复
热议问题