【发布时间】:2013-03-21 22:28:41
【问题描述】:
当使用单个共享变量递增和递减多个线程时,如何确保线程以同步方式计数并且不跳过任何值。
我创建了一个单独的类,其中我有 3 种不同的方法,一种用于递增,另一种用于递减,最后一种用于返回值。它们也都是同步的。
结果展示了一个例子:
- 这是 Thread_4 迭代:-108 of 500
这是 Thread_5 迭代:500 个中的 291 个
这是 Thread_4 迭代:-109 of 500
这是 Thread_4 迭代:-110 of 500
如您所见,线程正在递减,但随后会跳转到“291”,这在我使用共享变量时不应该发生。
*******************编辑**** ****
代码:- 共享变量类
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();
}
【问题讨论】:
-
不贴代码就无法判断
-
输入您的代码,让我们更好地了解您的问题。
-
预期输出是什么?
标签: java multithreading concurrency bluej