Java中的并发工具类

来源:互联网 发布:19楼网络股份有限公司 编辑:程序博客网 时间:2024/06/16 09:50

编写一个自定义同步组件来加深对同步器的理解
业务要求:
* 编写一个自定义同步组件来加深对同步器的理解。
* 设计一个同步工具:该工具在同一时刻,只允许至多两个线程同时访问,超过两个线程的
* 访问将被阻塞,我们将这个同步工具命名为TwinsLock。
* 首先,确定访问模式。TwinsLock能够在同一时刻支持多个线程的访问,这显然是共享式
* 访问,因此,需要使用同步器提供的acquireShared(int args)方法等和Shared相关的方法,这就要
* 求TwinsLock必须重写tryAcquireShared(int args)方法和tryReleaseShared(int args)方法,这样才能
* 保证同步器的共享式同步状态的获取与释放方法得以执行。
* 其次,定义资源数。TwinsLock在同一时刻允许至多两个线程的同时访问,表明同步资源
* 数为2,这样可以设置初始状态status为2,当一个线程进行获取,status减1,该线程释放,则
* status加1,状态的合法范围为0、1和2,其中0表示当前已经有两个线程获取了同步资源,此时
* 再有其他线程对同步状态进行获取,该线程只能被阻塞。在同步状态变更时,需要使用
* compareAndSet(int expect,int update)方法做原子性保障。
* 最后,组合自定义同步器。前面的章节提到,自定义同步组件通过组合自定义同步器来完
* 成同步功能,一般情况下自定义同步器会被定义为自定义同步组件的内部类

import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.AbstractQueuedSynchronizer;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;public class TwinsLock implements Lock {    private final  Sync sync = new Sync(2);    private static final class  Sync extends AbstractQueuedSynchronizer {        Sync(int count) {            if(count <= 0) {                throw  new IllegalArgumentException("count must large zero!");            }            setState(count);        }        //共享式同步状态的获取。        public int tryAcquireShared(int reduceCount) {            for(;;) { //自旋                int current = getState();                int newCount = current - reduceCount;                if(newCount < 0 || compareAndSetState(current, newCount)) {                    return newCount;                }            }        }        //共享式同步状态释放.        public boolean tryReleaseShared(int returnCount) {            for(;;) {//自旋.                int current = getState();                int newCount = current + returnCount;                if(compareAndSetState(current, newCount)) {                    return true;                }            }        }        final ConditionObject newCondition() {            return new ConditionObject();        }    }    //共享式获取    public void lock() {        sync.acquireShared(1);    }    public void lockInterruptibly() throws InterruptedException {        //和acquire方法相同, 但是该方法响应中段.        sync.acquireInterruptibly(1);    }    //如果返回大于等于0表示获取成功。    public boolean tryLock() {        return sync.tryAcquireShared(1) >= 0;    }    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {        return sync.tryAcquireSharedNanos(1, unit.toNanos(time));    }    //释放所资源    public void unlock() {        sync.releaseShared(1);    }    public Condition newCondition() {        return sync.newCondition();    }}

测试类:

import javafx.concurrent.Worker;import java.util.concurrent.locks.Lock;public class TwinsLockTest {    public  static  void main(String argc[]){        final Lock lock = new TwinsLock();        class Worker extends Thread{            public void run() {                while(true) {                    lock.lock();                    try {                            System.out.println(Thread.currentThread().getName());                            Thread.sleep(1500);                    } catch (InterruptedException e) {                       System.out.println("interruptException!");                    }                    finally {                        lock.unlock();                        break;                    }                }            }        }        for(int i = 0; i < 10; i++) {            Worker worker = new Worker();            //worker.setDaemon(true);            worker.start();        }        //每间隔一秒钟打印一个空行.        for(int i = 0; i <10; i++) {            try {                Thread.sleep(1000);            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println();        }    }}

1。等待多线程完成的CountDownLatch

/** * 利用join实现主线程等待其他线程执行完成. * parser1模拟一个任务 * parser2模拟一个稍微耗时的任务 * 两个线程执行完成才继续主线程的执行 * @author wangwenhao * */public class JoinCountDownLatchTest {    public static void main(String[] args) throws InterruptedException {        Thread parser1 = new Thread(new Runnable() {            @Override            public void run() {                for(int i = 0; i < Integer.MAX_VALUE; i++) {                }                System.out.println("parser1 finished!");            }        });        Thread parser2 = new Thread(new Runnable() {            @Override            public void run() {                for(int i = 0; i < 1000; i++) {                    try {                        Thread.sleep(2);                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }                System.out.println("parser2 finished!");            }        });        parser1.start();        parser2.start();        parser1.join();        parser2.join();        System.out.println("all parser finish!");    }}
import java.util.concurrent.CountDownLatch;import java.util.concurrent.TimeUnit;/** *  * @author wangwenhao * 1. 在JDK1.5之后的并法包中提供的CountDownLatch也可以实现join的功能,并且比join的功能更多 * 2. CountDownLatch的构造函数接收一个int类型的参数作为计数器,如果你想等待N个点完成, 这里就传入N。 * 3. 当我们调用CountDownLatch的countDown方法时,N就会减1,CountDownLatch的await方法会阻塞当前线程,直到N变为0. * 4. 由于CountDownLatchh方法可以用到任何地方,所以这里说的N个点,可以是N个线程, 也可以是1个线程里的N个步骤。 *    用在多个线程的时候,只需要把这个CountDownLatch的引用传递到线程里即可。 * 5. 如果有某个线程处理的特别慢, 我们不可能让主线程一直等待,  *    所以可以使用另外一个指定时间的await方法-await(long time, TimeUnit unit),这个方法等待特定时间后就不再阻塞当前线程, * join也有类似的方法. *  * */public class CountDownLatchTest {    static CountDownLatch count = new CountDownLatch(2);//  static CountDownLatch count = new CountDownLatch(3);    public static void main(String[] args) throws InterruptedException {        Thread thread1 = new Thread(new Runnable() {            @Override            public void run() {                System.out.println(1);                count.countDown();                try {                    Thread.sleep(8000);                } catch (InterruptedException e) {                    e.printStackTrace();                }                System.out.println(2);                count.countDown();            }        });        thread1.start();        count.await();//      count.await(5, TimeUnit.SECONDS);        System.out.println(3);    }}

2。同步屏障CyclicBarrier

import java.util.concurrent.CyclicBarrier;/** * 1. CyclicBarrier 让一组线程到达一个屏障(也可以叫同步点)时被阻塞,直到最后一个线程到达屏障时, * 屏障才会开门, 所有被屏障拦截的线程才可以继续运行. * 2. CyclicBarrier 默认的构造方法时 CyclicBarrier(int parties),  * 其参数代表屏障拦截的线程数量, 每一个线程调用await方法告诉CyclicBarrier我已经 * 到达了屏障, 然后当前线程被阻塞。 * 3.测试中一定会先输出1和4, 然后才会执行后面的。 * @author wangwenhao * */public class CyclicBarrierTest {//  static CyclicBarrier c = new CyclicBarrier(3); 将会永远阻塞    static CyclicBarrier c = new CyclicBarrier(2);    public static void main(String[] args) {        new Thread(new Runnable() {            @Override            public void run() {                try {                    Thread.sleep(2000);                    System.out.println(1);                    c.await();                    System.out.println(2);                } catch (Exception e) {                    e.printStackTrace();                }                 System.out.println(3);            }        }).start();        try {            System.out.println(4);            c.await();        } catch (Exception e) {            e.printStackTrace();        }        System.out.println(5);    }}

CyclicBarrier 应用场景:比如一个excel有4张sheet, 每个线程计算一张最后合并

import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CyclicBarrier;import java.util.concurrent.Executor;import java.util.concurrent.Executors;/** * CyclicBarrier 可以用于多线程计算数据, 最后合并计算的场景。 * 应用场景:比如一个excel有4张sheet, 每个线程计算一张最后合并 * @author  wangwenhao * */public class BankWaterService implements Runnable{    /*     * 创建4个屏障, 处理完之后执行当前类的run方法     */    private CyclicBarrier c = new CyclicBarrier(4, this);    /**     * 假设只有4个sheet,启动4个线程      */    private Executor executor = Executors.newFixedThreadPool(4);    /**     * 保存每个sheet计算出的结果     */    private ConcurrentHashMap<String, Integer> sheetBankWaterCount = new ConcurrentHashMap<>();    private void count() {        for(int i = 0; i < 4; i++) {            executor.execute(new Runnable() {                @Override                public void run() {                    /**                     * 计算当前sheet的结果, 计算代码省略.                     */                    sheetBankWaterCount.put(Thread.currentThread().getName(), 1);                    try {                        //计算结束插入屏障.                        c.await();                    }catch(InterruptedException | BrokenBarrierException e) {                        e.printStackTrace();                    }                }            });        }    }    @Override    public void run() {        int result = 0;        //汇总每一个sheet计算出的结果.        for(java.util.Map.Entry<String, Integer> sheet : sheetBankWaterCount.entrySet()) {            result += sheet.getValue();        }        //将结果输出。        sheetBankWaterCount.put("result", result);        System.out.println(result);    }    public static void main(String[] args) {        BankWaterService bankWaterService = new BankWaterService();        bankWaterService.count();    }}

3。控制并发线程数的Semaphore

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;/** * 1. Semaphore(信号量)是用来控制同时访问特定资源的线程数量, * 他通过协调各个线程以保证合理使用公共资源。  * 2. 代码中有60个线程,但是只运行10个并发执行。 * 3.Semaphore的acquire()方法获取一个许可证, 使用完之后调用release()方法归还许可证,  *   还可以使用tryAcquire()方法尝试获取许可证 * 4.release()归还后供其他线程获取许可证. * @author  wangwenhao * */public class SemaphoreTest {    private static final int THREAD_COUNT = 60;    private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);    //运行10个线程获取许可证, 也就是并发数是10.    private static Semaphore s = new Semaphore(10);    public static void main(String[] args) {        for(int i = 0; i < THREAD_COUNT; i++) {            threadPool.execute(new Runnable() {                @Override                public void run() {                    try{                        s.acquire();                        Thread.sleep(2000);                        System.out.println(Thread.currentThread().getName() + ": save data");                        s.release();                    } catch(InterruptedException e) {                        e.printStackTrace();                    }                }            });        }        threadPool.shutdown();    }}

4。线程间交换数据的Exchanger

import java.util.concurrent.Exchanger;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** *1. Exchanger用于进行线程间的数据交换, 它提供一个同步点, 在这个同步点,两个线程可以交换彼此的数据 *2. 两个线程通过 Exchanger交换数据, 如果第一个线程先执行exchange()方法, *   它会一直等待第二个线程也执行exchange()方法, 当两个线程到达同步点时, 这两个线程就可以交换数据。 * @author  wangwenhao * */public class ExchangerTest {    private static final Exchanger<String> exgr = new Exchanger<>();    private static ExecutorService threadPool = Executors.newFixedThreadPool(2);    public static void main(String[] args) {        threadPool.execute(new Runnable() {            @Override            public void run() {                try{                    String A = "银行流水AA";                    Thread.sleep(2000);                    String B = exgr.exchange(A);                    System.out.println("B: " + B);                }catch(InterruptedException e) {                    e.printStackTrace();                }            }        });        threadPool.execute(new Runnable() {            @Override            public void run() {                try {                    String B = "银行流水B";                    Thread.sleep(5000);                    String A = exgr.exchange(B);                    System.out.println("A和B数据是否一致: " + A.equals(B) + ",                     A录入的是:" + A + ", B录入的是: " + B);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        });        threadPool.shutdown();    }}

备注:本文参考《并发编程的艺术》第8章节!

原创粉丝点击