JAVA线程10 - 新特性:原子量

1、原子量简介

原子量就是操做变量的操做是“原子的”,该操做不可再分,所以是线程安全的。 java

原子量虽然能够保证单个变量在某一个操做过程的安全,但没法保证你整个代码块,或者整个程序的安全性。所以,一般还应该使用锁等同步机制来控制整个程序的安全性。

2、原子量的做用

多个线程对单个变量操做也会引发一些问题。在Java5以前,能够经过volatile、synchronized关键字来解决并发访问的安全问题,但这样太麻烦。
Java5以后,专门提供了用来进行单变量多线程并发安全访问的工具包java.util.concurrent.atomic。

3、使用示例

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();
    }

}
相关文章
相关标签/搜索