Java編程思想-java中的並發(四)__演算法

來源:互聯網
上載者:User
五、 新類庫中的構件

Java SE5的java.util.concurrent引入了大量設計用來解決並發問題的新類。學習使用它們將有助於編寫出更加簡單而強壯的並發程式。 1. CountDownLatch

他被用來同步一個或多個任務,強制他們等待由其他任務執行的一組操作完成。

你可以向CountDownLatch對象設定一個初始計數值,任何在這個對象上調用wait()方法都將阻塞,直至這個計數值到達0。其他任務在結束其工作時,可以在該對象上盜用countDown()來減小這個計數值。CountDownLatch被設計為只觸發一次,計數值不能被重設。如果你需要能夠重設計數值的版本,則可以使用CyclicBarrier。

調用countDown()的任務在產生這個調用時並沒有被阻塞,只有對await()的調用會被阻塞,直至計數值到達0。

CountDownLatch的典型用法是將一個程式氛圍n個相互獨立的可解決任務,並建立值為0的CountDownLatch。當每個任務完成時,都會在這個鎖存器上調用countDown()。等待問題唄解決的任務在這個鎖存器上調用await(),將他們自己攔住,直至鎖存器計數結束。下面是示範這種技術的一個架構樣本:

public class CountDownLatchDemo {    static final int SIZE = 100;    public static void main(String[] args) throws Exception {        ExecutorService exec = Executors.newCachedThreadPool();        CountDownLatch latch = new CountDownLatch(SIZE);        for (int i = 0; i < 10; i++) {            exec.execute(new WaitingTask(latch));        }        for (int i = 0; i < SIZE; i++) {            exec.execute(new TaskPortion(latch));        }        System.out.println("Launched all tasks");        exec.shutdown();    }}class TaskPortion implements Runnable {    private static int counter = 0;    private final int id = counter++;    private static Random rand = new Random(47);    private final CountDownLatch latch;    TaskPortion(CountDownLatch latch) {        this.latch = latch;    }    public void run() {        try {            doWork();            latch.countDown();        } catch (InterruptedException e) {            //Acceptable way to exit        }    }    public void doWork() throws InterruptedException {        TimeUnit.MILLISECONDS.sleep(rand.nextInt(2000));        System.out.println(this + "completed");    }    public String toString() {        return String.format("%1$-3d", id);    }}class WaitingTask implements Runnable {    private static int counter = 0;    private final int id = counter++;    private final CountDownLatch latch;    WaitingTask(CountDownLatch latch) {        this.latch = latch;    }    public void run() {        try {            latch.await();            System.out.println("Latch barrier passed for " + this);        } catch (InterruptedException e) {            System.out.println(this + " interrupted");        }    }    public String toString() {        return String.format("WaitingTask %1$-3d", id);    }}

TaskPortion將隨機的休眠一段時間,以類比這部分工作的完成,而WaitingTask表示系統中必須等待的部分,它要等待到問題的初始部分完成為止。所有任務都使用了在main()中定義的同一個單一的CountDownLatch。 2. CyclicBarrier

CyclicBarrier適用於這樣的情況,你希望建立一組任務,他們並行的執行任務,然後在進行下一個步驟前等待,直至所有任務都完成(看起來有些像join())。它使得所有的並行任務都在柵欄處列隊,因此可以一致的向前移動。這非常像CountDownLatch,只是CountDownLatch是只觸發一次的事件,而CyclicBarrier可以多次重用。

public class HorseRace {    static final int FINISH_LINE = 75;    private List<Horse> horses = new ArrayList<Horse>();    private ExecutorService exec = Executors.newCachedThreadPool();    private CyclicBarrier barrier;    public HorseRace(int nHorses, final int pause) {        barrier = new CyclicBarrier(nHorses, () -> {            StringBuilder s = new StringBuilder();            for (int i = 0; i < FINISH_LINE; i++) {                s.append("=");            }            System.out.println(s);            for (Horse horse : horses) {                System.out.println(horse.tracks());            }            for (Horse horse : horses) {                if (horse.getStrides() >= FINISH_LINE) {                    System.out.println(horse + " won!");                    exec.shutdownNow();                    return;                }            }            try {                TimeUnit.MILLISECONDS.sleep(pause);            } catch (InterruptedException e) {                System.out.println("barrier-action sleep interrupted");            }        });        for (int i = 0; i < nHorses; i++) {            Horse horse = new Horse(barrier);            horses.add(horse);            exec.execute(horse);        }    }    public static void main(String[] args) {        int nHorses = 7;        int pause = 200;        if (args.length > 0) {            int n = new Integer(args[0]);            nHorses = n > 0 ? n : nHorses;        }        if (args.length > 1) {            int p = new Integer(args[1]);            pause = p > -1 ? p : pause;        }        new HorseRace(nHorses, pause);    }}class Horse implements Runnable {    private static int counter = 0;    private final int id = counter++;    private int strides = 0;    private static Random rand = new Random(47);    private static CyclicBarrier barrier;    public Horse(CyclicBarrier barrier) {        this.barrier = barrier;    }    public synchronized int getStrides() {        return strides;    }    public void run() {        try {            while (!Thread.interrupted()) {                synchronized (this) {                    strides += rand.nextInt(3);                }                barrier.await();            }        } catch (InterruptedException e) {            //a legitimate way to exit        } catch (BrokenBarrierException e) {            //This one we want to know about            throw new RuntimeException(e);        }    }    public String toString() {        return "Horse " + id + "  ";    }    public String tracks() {        StringBuilder s = new StringBuilder();        for (int i = 0; i < getStrides(); i++) {            s.append("*");        }        s.append(id);        return s.toString();    }}

可以向CyclicBarrier提供一個“柵欄動作”,他是一個Runnable,當計數值到達0時自動執行–這是CyclicBarrier和CountDownLatch之間的另一個區別。這裡,柵欄動作是作為匿名內部類建立的,他被提交給了CyclicBarrier的構造器。 3. DelayQueue

這是一個無界的BlockingQueue,用於放置實現了Delayed介面的對象,其中的對象只能在其到期時才能從隊列中取走。這種隊列是有序的,即隊頭對象的延遲到期的時間最長。如果沒有任何延遲到期,那麼就不會y任何頭元素,並且poll()將返回null(正因為這樣,你不能將null放置到這種隊列中)。 4. Semaphore

正常的鎖在任何時刻都只允許yi’ge’ren’wu一個任務訪問一項資源,而計數訊號量允許n個任務同時訪問這個資源。你還可以將訊號量看作是在向外分發使用資源的“許可證”,儘管實際上沒有使用任何許可證對象。

作為一個樣本,請考慮對象池的概念,他管理著數量有限的對象,當要使用對象時可以簽出他們,而在使用者使用完畢時,可以將他們簽回。這種功能可以被封裝到一個泛型類中:

public class Pool<T> {    private int size;    private List<T> items = new ArrayList<T>();    private volatile boolean[] checkedOut;    private Semaphore available;    public Pool(Class<T> classObject, int size) {        this.size = size;        checkedOut = new boolean[size];        available = new Semaphore(size, true);        for (int i = 0; i < size; i++) {            try {                items.add(classObject.newInstance());            } catch (Exception e) {                throw new RuntimeException(e);            }        }    }    public T checkOut() throws InterruptedException {        available.acquire();        return getItem();    }    public void checkIn(T x) {        if (releaseItem(x)) {            available.release();        }    }    private synchronized T getItem() {        for (int i = 0; i < size; i++) {            if (!checkedOut[i]) {                checkedOut[i] = true;                return items.get(i);            }        }        return null;    }    private synchronized boolean releaseItem(T item) {        int index = items.indexOf(item);        if (index == -1) {            return false;        }        if (checkedOut[index]) {            checkedOut[index] = false;            return true;        }        return false;    }}

在這個簡化的形式中,構造器使用newInstance()來把對象載入到池中。如果你需要一個新對象,那麼可以調用checkOut(),並且在使用完之後,將其遞交給checkIn()。

為了建立一個樣本,我們可以使用Fat,這是一種建立代價高昂的物件類型,因為他的構造器運行起來很耗時:

public class Fat {    private volatile double d;    private static int counter = 0;    public Fat() {        for (int i = 1; i < 10000; i++) {            d += (Math.PI + Math.E) / (double) i;        }    }    public void operation() {        System.out.println(this);    }    public String toString() {        return "Fat id: " + d;    }}

我們在池中管理這些對象,以限制這個構造器所造成的影響。我們可以建立一個任務,它將簽出Fat對象,持有一段時間後再將他們簽入,以此來測試Pool這個類:

public class SemaphoreDemo {    final static int SIZE = 25;    public static void main(String[] args) throws Exception {        final Pool<Fat> pool = new Pool<>(Fat.class, SIZE);        ExecutorService exec = Executors.newCachedThreadPool();        for (int i = 0; i < SIZE; i++) {            exec.execute(new CheckoutTask<Fat>(pool));        }        System.out.println("All CheckoutTasks created");        List<Fat> list = new ArrayList<>();        for (int i = 0; i < SIZE; i++) {            Fat f = pool.checkOut();            System.out.println(i + ": main() thread checked out");            f.operation();            list.add(f);        }        Future<?> blocked = exec.submit(new Runnable() {            public void run() {                try {                    pool.checkOut();                } catch (InterruptedException e) {                    System.out.println("checkout() interrupted");                }            }        });        TimeUnit.SECONDS.sleep(2);        blocked.cancel(true);        System.out.println("Checking in objects in " + list);        for (Fat f : list) {            pool.checkIn(f);        }        for (Fat f : list) {            pool.checkIn(f);        }        exec.shutdown();    }}class CheckoutTask<T> implements Runnable {    private static int counter = 0;    private final int id = counter++;    private Pool<T> pool;    public CheckoutTask(Pool<T> pool) {        this.pool = pool;    }    public void run() {        try {            T item = pool.checkOut();            System.out.println(this + " checked out " + item);            TimeUnit.SECONDS.sleep(1);            System.out.println(this + " checked in " + item);            pool.checkIn(item);        } catch (InterruptedException e) {            //Acceptable way to terminate        }    }    public String toString() {        return "CheckoutTask " + id + "  ";    }}

在main()中,建立了一個持有Fat對象的Pool,而一組CheckoutTask則開始操練這個Pool。然後,main()線程簽出池中的Fat對象,但是並不簽入他們。一旦池中所有的對象都被簽出,Semaphore將不再允許執行任何簽出操作。blocked的run()方法因此會被阻塞,2秒之後,cancel()方法被調用,以此來掙脫Future的束縛。注意,冗餘的qian’ru簽入將被Pool忽略。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.