Java 为什么';这个循环不能执行1000次吗?
我希望编译器为每个线程运行1000次循环,但输出是12次。为什么会这样Java 为什么';这个循环不能执行1000次吗?,java,Java,我希望编译器为每个线程运行1000次循环,但输出是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;
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();
}
}
public类Runy实现Runnable{
int x,y;
公开募捐{
对于(int i=0;i<1000;i++)
已同步(此){
x=12;
y=12;
}
系统输出打印(x+“”+y+“”);
}
公共静态void main(字符串参数[]){
Runy run=新Runy();
线程t1=新线程(运行);
螺纹t2=新螺纹(运行);
t1.start();
t2.start();
}
}
问题在于您的for循环
for (int i = 0; i < 1000; i++)
synchronized (this) {
x = 12;
y = 12;
}
System.out.print(x + " " + y + " ");
应该为您提供4000个
12
检查您的循环(int i=0;i<1000;i++)
ayyyyyyyy!我刚才看到了@MadProgrammer所指的内容。提示:代码完全按照您所说的做了to@prabhakarReddyG您的编辑修改了代码,因此问题的原始上下文已丢失(但执行是相同的),请小心编辑;编辑实际上设法掩盖了这里的实际问题。即使是问题的原始版本,其System.out.print
缩进与for
循环缩进相同,那么为什么您认为它应该位于循环内部?“这个问题实际上并没有说这就是我们的意图。”安德烈亚斯,因为否则,为什么要问这个问题?OP想知道为什么它“只打印”12
,这让我相信他们希望在loop@Andreas看了之后,我不想记得有多少问题,关于为什么if
和loop
由于缺少{…}而不能按预期工作
你只是假设是的,我知道,这是一个显而易见的假设,但它仍然是一个假设。OP也可能打算写+=12
,并期望结果是12000或24000左右,但这只是另一种可能性。问题不清楚,因此应关闭(MCVE)。鉴于压痕,我不确定你的假设是否正确,但除非OP告诉我们,否则我们永远不会知道。是的,2票:MCVE和Down。哦,还有答案,尽管我认为你跳到了假设上
for (int i = 0; i < 1000; i++) {
synchronized (this) {
x = 12;
y = 12;
}
}
System.out.print(x + " " + y + " ");
for (int i = 0; i < 1000; i++) {
synchronized (this) {
x = 12;
y = 12;
}
System.out.print(x + " " + y + " ");
}