为什么我不能中断 Java 循环



即使我使用了synchronized,我也无法到达代码中的最后一行。但是,如果我在循环之间添加一些东西,效果很好。

public static void main(String[] args) {
    int test_time = 5;
    for (int i = 0; i < 100000; i++) {
        //warm up
    }
    long t = 0;
    t = System.currentTimeMillis();
    byte[] b = new byte[0];
    for (int i = 0; i < test_time; i++) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String i = getUserInf(); //get something from web
                synchronized (b) {
                    ++times;
                    System.out.println(times);
                }
            }
        }).start();
    }
    while (times != test_time){
        // System.out.println(String.format("times=%s,test_time=%s", times,test_time));     
        // if i added this line, it worked well
    }
    System.out.println("time:" + (System.currentTimeMillis() - t));
}
您需要

将变量times声明为 volatile int 。因为当它在 while 循环中从主线程读取时,它不受 b 的保护。对System.out.println的调用是同步的,因此times的值会更新并变得可见。

最新更新