新特徵-原子量

package atomic;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Java線程:新特徵-原子量
*/
public class Test {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        Runnable t1 = new MyRunnable("張三", 2000);
        Runnable t2 = new MyRunnable("李四", 3600);
        Runnable t3 = new MyRunnable("王五", 2700);
        Runnable t4 = new MyRunnable("老張", 600);
        Runnable t5 = new MyRunnable("老牛", 1300);
        Runnable t6 = new MyRunnable("胖子", 800);
        // 執行各個線程
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.execute(t5);
        pool.execute(t6);
        // 關閉線程池
        pool.shutdown();
    }
}

class MyRunnable implements Runnable {
    // 原子量,每個線程都可以自由操作
    private static AtomicLong aLong = new AtomicLong(10000);
    private String name; // 操作人
    private int x; // 操作數額

    MyRunnable(String name, int x) {
        this.name = name;
        this.x = x;
    }

    public void run() {
        System.out.println(name + "執行了" + x + ",當前餘額:" + aLong.addAndGet(x));
    }
}

從運行結果可以看出,雖然使用了原子量,但是程序併發訪問還是有問題,那究竟問題出在哪裏了?

這裏要注意的一點是,原子量雖然可以保證單個變量在某一個操作過程的安全,但無法保證你整個代碼塊,或者整個程序的安全性。因此,通常還應該使用鎖等同步機制來控制整個程序的安全性。

下面是對這個錯誤修正:

package atomic;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestThread {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        Lock lock = new ReentrantLock(false);
        Runnable t1 = new MyTRunnable("張三", 2000, lock);
        Runnable t2 = new MyTRunnable("李四", 3600, lock);
        Runnable t3 = new MyTRunnable("王五", 2700, lock);
        Runnable t4 = new MyTRunnable("老張", 600, lock);
        Runnable t5 = new MyTRunnable("老牛", 1300, lock);
        Runnable t6 = new MyTRunnable("胖子", 800, lock);
        // 執行各個線程
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.execute(t5);
        pool.execute(t6);
        // 關閉線程池
        pool.shutdown();
    }
}

class MyTRunnable implements Runnable {
    // 原子量,每個線程都可以自由操作
    private static AtomicLong aLong = new AtomicLong(10000);
    private String name; // 操作人
    private int x; // 操作數額
    private Lock lock;

    MyTRunnable(String name, int x, Lock lock) {
        this.name = name;
        this.x = x;
        this.lock = lock;
    }

    public void run() {
        lock.lock();
        System.out.println(name + "執行了" + x + ",當前餘額:" + aLong.addAndGet(x));
        lock.unlock();
    }

}

這裏使用了一個對象鎖,來控制對併發代碼的訪問。不管運行多少次,執行次序如何,最終餘額均爲21000,這個結果是正確的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章