2013-03-31 39 views
0

当递增和递减使用单一的共享变量多线程,我怎么能保证线程在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(); 
} 
+2

无法发布代码 –

+2

把你的代码让我们更好地理解你的问题。 –

+0

预期产量是多少? – fish

回答

5

考虑使用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; 
    } 
} 
+0

我已经做到了这一点,我仍然没有得到完全同步的递增和递减计数。 *****(这是Thread_2迭代:-9 500) This is Thread_2 iteration:-8 of 500 This is Thread_1 iteration:-135 of 500这是Thread_1迭代:-7 of 500 这是Thread_1迭代:-6 of 500) – user2075927

+0

是否可以在一种方法中运行增量和减量而不是使用两种不同的方法? – user2075927

0

不知道我是否正确理解你的问题,但是你的输出看起来就是因为另一个线程(Thread_4)在Thread_5输出它之前处理该值。

有打算多项业务在每次迭代(简体名单,在现实中有不止这些):

  1. 递增/递减
  2. 获取当前值
  3. 创建输出字符串
  4. 输出输出字符串

而另一个线程可以得到任何这些运之间的转操作。所以可能是因为Thread_5做了它所做的事情,然后其他线程会转向,并且只有在Thread_5输出结果之后。

如果您希望按顺序输出新值,则需要在同步块内输出当前值,即。增量/减量方法。

+0

我想我明白你的意思,能否看到一个例子呢? – user2075927

+0

是否可以在一种方法中运行递增和递减,而不是使用两种不同的方法? – user2075927

+0

只需将System.out.println放入increment()或decrement()。如果您想对两种操作使用一种方法,请使用方法参数来指示它是哪种操作。像操作(布尔增量)一样。 – fish