我希望编译器为每个线程运行1000次循环,但输出为12 12 12 12.为什么会发生这种情况?
public class Runy implements Runnable {
int x, y;
public void run() {
for (int i = 0; i < 1000; i++)
synchronized (this) {
x = 12;
y = 12;
}
System.out.print(x + " " + y + " ");
}
public static void main(String args[]) {
Runy run = new Runy();
Thread t1 = new Thread(run);
Thread t2 = new Thread(run);
t1.start();
t2.start();
}
}
Run Code Online (Sandbox Code Playgroud)
问题出在你for-loop身上......
for (int i = 0; i < 1000; i++)
synchronized (this) {
x = 12;
y = 12;
}
System.out.print(x + " " + y + " ");
Run Code Online (Sandbox Code Playgroud)
这是一样的
for (int i = 0; i < 1000; i++) {
synchronized (this) {
x = 12;
y = 12;
}
}
System.out.print(x + " " + y + " ");
Run Code Online (Sandbox Code Playgroud)
现在应该突出问题.基本上,没有{...}块,只有synchornized循环执行块,1000次.
就像是...
for (int i = 0; i < 1000; i++) {
synchronized (this) {
x = 12;
y = 12;
}
System.out.print(x + " " + y + " ");
}
Run Code Online (Sandbox Code Playgroud)
应该为你提供4000 12的
| 归档时间: |
|
| 查看次数: |
126 次 |
| 最近记录: |