use*_*927 0 java concurrency multithreading bluej
当递增和使用一个单一的共享变量递减多线程,我怎么能保证线程在syncronized方式计算,不跳过任何价值.
我创建了一个单独的类,其中有3个不同的方法,一个用于递增,另一个用于递减,最后一个用于返回值.它们都是同步的.
结果显示了一个例子:
正如您所看到的那样,线程正在递减,但随后它会跳转到"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;
}
}
Run Code Online (Sandbox Code Playgroud)
-----递增类
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();
}
Run Code Online (Sandbox Code Playgroud)
考虑使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
或使用同步方法:
public class Foo
{
private volatile int counter;
public synchronized void increment()
{
counter++;
}
public synchronized void decrement()
{
counter--;
}
public int getValue()
{
return counter;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10012 次 |
| 最近记录: |