![](/img/trans.png)
[英]Why can't this for loop be broken with 'break' or by exceeding limit? - Java
[英]Why can't I break the Java loop
即使我使用了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
值会更新并变为可见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.