我的程序没有返回预期的输出,我非常努力,但我不知道如何处理这段代码。我能做什么?
预期输出
1 2 3 4 5 6 7 8 ......2000
实际输出
1 2 3 4 5 6 1 2 3 4 5 6 ..1000
主要
public class Race_ConditonTest {
public static void main(String[] args) {
Race_Condition2 R1 = new Race_Condition2();
Race_Condition2 R2 = new Race_Condition2();
R1.start();
R2.start();
}
}
RaceCondition2(子类)
public class Race_Condition2 extends Thread{
Race_Condition R= new Race_Condition();
public void run() {
R.sum();
}
}
RaceCondition类(父类(super class))
public class Race_Condition {
int x=0;
public int Load(int x){
return x;
}
public void Store(int data) {
int x= data;
System.out.println(x);
}
public int Add(int i,int j) {
return i+j ;
}
public void sum() {
for (int i=0 ; i<1000 ; i++) {
this.x=Load(x);
this.x=Add(x,1);
Store(x);
}
}
}
最佳答案
how can i share x ?
简单的方法>使x
静态。
...
静态 int x=0;
... 编辑
经过一些测试,如果您发现发生奇怪的情况,请同步 Store 功能。
public synchronized void Store(int data) {
int x= data;
System.out.println(x);
}
查看同步如何工作 synchronized
关于java - java线程的共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49366337/