java - 使用多个线程递增和递减单个共享变量

标签 java multithreading concurrency bluej

当使用单个共享变量递增和递减多个线程时,如何确保线程以同步方式计数并且不跳过任何值。

我创建了一个单独的类,其中有 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/

相关文章:

java - 是否可以通过使用 AtomicInteger 的方法来改变 int ?

java - 如果你已经结束了,将 null 分配给 java CDI/EJB bean 引用是一个好习惯吗?

c++ - lock_guard always owns the lock mode of the referenced mutex 是什么意思?

c++ - 如何正确地将参数传递给 pthread

loops - 是否可以从外部功能停止股票行情/股票报价?

javascript - Q promise 中的并发限制 - Node

java - 如何找到与另一个表中的时间戳最接近的表中的时间戳(MySQL)

java - 如何使用默认模型表更新和检测选中的复选框

multithreading - pthread健壮的互斥锁有多安全?

c# - 如何创建无重复的ConcurrentQueue?