Java并发编程(五)《并发工具类》

来源:互联网 发布:手机数据共享 编辑:程序博客网 时间:2024/05/17 04:56

  • Java并发编程五并发工具类
    • 1等待多线程完成的CountDownLatch
    • 2同步屏障CyclicBarrier
    • 3控制并发线程数的Semaphore
    • 4线程间数据的切换Exchanger

Java并发编程(五)《并发工具类》

@(并发)

5.1.等待多线程完成的CountDownLatch

package com.tjp.thead.lock;import java.util.concurrent.CountDownLatch;/** * Created by TJP on 2017/1/4. */public class CountDownLatchTest {    /**     * CountDownLatch允许一个或多个线程等待其他线程完成操作后执行     * 共享模式,初始化同步状态为2     */    private static CountDownLatch cdl = new CountDownLatch(2);    public static void main(String[] args) throws InterruptedException {        new Thread(new Runnable() {            public void run() {                System.out.println(2);                /**                 * countDown释放同步状态state-1                 */                cdl.countDown();                System.out.println(Thread.currentThread().getName() + " call countDown ,release lock state-1 , state : " + 1);                /**                 * countDown释放同步状态state-1                 * 释放直到state=0,才tryReleaseShared成功,唤醒同步队列的头结点等待的线程                 */                cdl.countDown();                System.out.println(Thread.currentThread().getName() + " call countDown ,release lock state-1 , state : " + 0);            }        }, "CountDownLatchTest-thread-01").start();        /**         * state=0时,线程不会在此阻塞         */        cdl.await();        System.out.println("state=0,main thread start");    }}

5.2.同步屏障CyclicBarrier

5.3.控制并发线程数的Semaphore

package com.tjp.thead.lock;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;/** * Semaphore信号量并发组件:共享模式,控制并发线程数 * Created by TJP on 2017/1/5. */public class SemaphoreTest {    private static final int THREAD_COUNT = 20;    public static void main(String[] args) {        //线程池        ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);        //只能5个线程同时访问        final Semaphore semaphore = new Semaphore(5);        // 模拟20个客户端同时访问        for (int i = 0; i < THREAD_COUNT; i++) {            final int no = i;            threadPool.execute(new Runnable() {                public void run() {                    try {                        /**                         * acquire获取许可 state-1                         * 当state<0,线程阻塞                         */                        semaphore.acquire();                        System.out.println("Accessing : " + no);                        Thread.sleep(3000);//模拟业务操作                        /**                         * release释放许可 state+1                         * 当state<0,线程阻塞                         */                        semaphore.release();                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            });        }        threadPool.shutdown();    }}

5.4.线程间数据的切换Exchanger