当使用单个共享变量递增和递减多个线程时,如何确保线程以同步方式计数并且不跳过任何值。
我创建了一个单独的类,其中有 3 种不同的方法,一种用于递增,另一种用于递减,最后一种用于返回值。它们也都是同步的。
结果显示示例:
- 这是 Thread_4 迭代:-108,共 500
这是 Thread_5 迭代:第 291 次,共 500 次
这是 Thread_4 迭代:-109/500
这是 Thread_4 迭代:-110/500
正如您所看到的,线程正在递减,但随后它跳转到“291”,这不应该发生,因为我使用的是共享变量。
********* **********编辑***< em>*****
代码:-共享变量类
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();
}
最佳答案
考虑使用AtomicInteger
:
public class Foo
{
private AtomicInteger counter = new AtomicInteger(0);
public void increment()
{
counter.incrementAndGet();
}
public void decrement()
{
counter.decrementAndGet();
}
public int getValue()
{
return counter.get();
}
}
<小时/>
或使用同步方法:
public class Foo
{
private volatile int counter;
public synchronized void increment()
{
counter++;
}
public synchronized void decrement()
{
counter--;
}
public int getValue()
{
return counter;
}
}
关于java - 使用多个线程递增和递减单个共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15733434/