我已经阅读了 java.util.concurrent 包的 API 文档,但显然误解了一些东西。概述说
一个小的类工具包,支持对单个变量进行无锁线程安全 编程。
但是,一个小型测试应用程序表明 AtomicInteger 类不提供线程安全性,至少在跨线程共享时(我接受 getAndSet / increment 方法本身至少是原子的)
测试:
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 变量时我没有得到一致的结果吗?我是否误解了线程安全保证?