当递增和递减使用单一的共享变量多线程,我怎么能保证线程在syncronized方式计算,不跳过任何值的单个共享变量。递增和decremening多线程
我已经创建的,我有3个不同的方法,一来增加一个独立的类,另一个递减,最后一个返回值。它们都是同步的。
结果显示了一个示例:
- 这是Thread_4迭代:500
这-108是Thread_5迭代:500
这291是Thread_4迭代:500
-109这是-110 500
的正如你可以看到线程正在递减,但随后跳转到“291”,因为我使用的是共享变量,它不应该发生:Thread_4迭代。
** * ** * ** * ** * ** * ****编辑* ** * * ***
CODE: - 共享变量CLASS
public class shareVar extends Thread
{
private static int sharedVariable = 0;
public synchronized static void increment(){
sharedVariable++;
}
public synchronized static void decrement(){
sharedVariable--;
}
public static int value(){
return sharedVariable;
}
}
-----递增类
sVar incrementVal = new sVar();
public synchronized void display(){
for(int countVal = 0; countVal<=max; countVal++){
incrementVal.increment();
System.out.println("This is " + threadName + " iteration: " + incrementVal.value() + " of " + max);
//this.yield();
}
System.out.println("*THIS " + threadName + " IS FINISH "
+ "INCREMENTING *");
}
public void run(){
display();
}
无法发布代码 –
把你的代码让我们更好地理解你的问题。 –
预期产量是多少? – fish