AtomicInteger是原子类,线程应该是安全的,为什么这种情况下,导致了线程不安全?
class MyThread111 implements Runnable{
AtomicInteger count = new AtomicInteger(10);
@Override
public void run() {
count.decrementAndGet();
System.out.println("线程" +Thread.currentThread().getName() + "购票成功,剩余:" + count);
}
public static void main(String[] args) {
MyThread111 myThread1 = new MyThread111();
Thread thread = new Thread(myThread1);
Thread thread2 = new Thread(myThread1);
Thread thread3 = new Thread(myThread1);
thread.start();
thread2.start();
thread3.start();
}
}
运行结果:
线程Thread-0购票成功,剩余:8
线程Thread-2购票成功,剩余:7
线程Thread-1购票成功,剩余:8
期望值是:
线程Thread-0购票成功,剩余:8
线程Thread-2购票成功,剩余:7
线程Thread-1购票成功,剩余:9
为什么运行的结果是线程不安全的呢? AtomicInteger是线程安全的啊