原子量就是操做變量的操做是「原子的」,該操做不可再分,所以是線程安全的。 java
原子量雖然能夠保證單個變量在某一個操做過程的安全,但沒法保證你整個代碼塊,或者整個程序的安全性。所以,一般還應該使用鎖等同步機制來控制整個程序的安全性。AtomicRunnable.java 安全
public class AtomicRunnable implements Runnable { private static AtomicInteger amount = new AtomicInteger(1000); // 原子量,每一個線程均可以自由操做 private Integer num; AtomicRunnable(Integer num) { this.num = num; } public void run() { synchronized(AtomicRunnable.class){ Integer result = amount.addAndGet(num); System.out.println(Thread.currentThread().getName()+"使用" + num + "更新了總數,當前總數爲:" + result); } } }AtomicTest.java
public class AtomicTest { public static void main(String[] args) throws InterruptedException { Runnable r1 = new AtomicRunnable(10); Runnable r2 = new AtomicRunnable(20); Runnable r3 = new AtomicRunnable(30); Runnable r4 = new AtomicRunnable(40); Runnable r5 = new AtomicRunnable(50); Runnable r6 = new AtomicRunnable(60); Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); Thread t3 = new Thread(r3); Thread t4 = new Thread(r4); Thread t5 = new Thread(r5); Thread t6 = new Thread(r6); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t6.start(); } }