我已经阅读了java.util.concurrent包的API文档,但显然误解了一些东西。概述说
支持对单变量进行无锁线程安全编程的小类工具包。
但是,一个小型测试应用程序表明,AtomicInteger类不提供线程安全性,至少当它在线程之间共享时是这样(我承认getAndSet /增量方法本身至少是原子)。
测试:
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntTest
{
public static void main(String[] args) throws InterruptedException
{
AtomicInteger atomicInt = new AtomicInteger(0);
WorkerThread w1 = new WorkerThread(atomicInt);
WorkerThread w2 = new WorkerThread(atomicInt);
w1.start();
w2.start();
w2.join(); // <-- As pointed out by StuartLC and BarrySW19, this should be w1.join(). This typo allows the program to produce variable results because it does not correctly wait for *both* threads to finish before outputting a result.
w2.join();
System.out.println("Final value: " + atomicInt.get());
}
public static class WorkerThread extends Thread
{
private AtomicInteger atomicInt = null;
private Random random = new Random();
public WorkerThread(AtomicInteger atomicInt)
{
this.atomicInt = atomicInt;
}
@Override
public void run()
{
for (int i = 0; i < 500; i++)
{
this.atomicInt.incrementAndGet();
try
{
Thread.sleep(this.random.nextInt(50));
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}当我运行这个类时,我总是得到950到1000之间的结果,而我总是希望看到的是1000。
当两个线程访问这个共享的AtomicInteger变量时,您能解释为什么我没有得到一致的结果吗?我是否误解了线程安全保证?
发布于 2015-03-20 12:18:49
看起来就像一个简单的剪切和粘贴错误--你要两次加入线程"w2“,而不是"w1”。目前,您希望线程"w1“在打印'final‘值时仍能运行一半时间。
https://stackoverflow.com/questions/29166168
复制相似问题