博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java并发编程:CountDownLatch、CyclicBarrier和Semaphore
阅读量:4683 次
发布时间:2019-06-09

本文共 6613 字,大约阅读时间需要 22 分钟。

参考

CountDownLatch用法

CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能。比如有一个任务A,它要等待其他4个任务执行完毕之后才能执行,此时就可以利用CountDownLatch来实现这种功能了。

CountDownLatch类只提供了一个构造器:

 public CountDownLatch(int count) { }; //参数count为计数值 

然后下面这3个方法是CountDownLatch类中最重要的方法:

public void await() throws InterruptedException { };   //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行public boolean await(long timeout, TimeUnit unit) throws InterruptedException { };  //和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行public void countDown() { };  //将count值减1

Demo:

1 package com.zxd.concurrent.learning; 2  3 import java.util.concurrent.CountDownLatch; 4  5 /** 6  * @Project ConcurrentLearning 7  * @Package com.zxd.concurrent.learning 8  * @Author:zouxiaodong 9  * @Description:10  * @Date:Created in 10:57 2018/3/21.11  */12 public class CountDownLatchTest {13 14     public static void main(String[] args) throws InterruptedException {15         System.out.println("主线程"+Thread.currentThread().getName()+"正在执行.......");16         CountDownLatch latch = new CountDownLatch(2);17         ThreadTest test_1 = new ThreadTest(latch,3000);18         ThreadTest test_2 = new ThreadTest(latch,5000);19         test_1.start();20         test_2.start();21         System.out.println("等待2个子线程执行完毕........");22         latch.await();23         System.out.println("2个子线程已经执行完毕..................");24         System.out.println("继续执行主线程..................");25         System.out.println("主线程其他逻辑执行..................");26     }27 }28 29 class ThreadTest extends Thread{30     private CountDownLatch countDownLatch = null;31     private long sleep = 0L;32 33     public ThreadTest(CountDownLatch countDownLatch,long sleep) {34         this.countDownLatch = countDownLatch;35         this.sleep = sleep;36     }37 38     @Override39     public void run() {40         try {41             System.out.println("子线程"+Thread.currentThread().getName()+"正在执行.......");42             Thread.sleep(sleep);43             System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕.......");44             System.out.println("--------------countDownLatch.getCount()前="+countDownLatch.getCount());45             countDownLatch.countDown();46             System.out.println("--------------countDownLatch.getCount()后="+countDownLatch.getCount());47         } catch (InterruptedException e) {48             e.printStackTrace();49         }50     }51 }
CountDownLatch

运行结果:


 

CyclicBarrier用法

字面意思回环栅栏,通过它可以实现让一组线程等待至某个状态之后再全部同时执行。叫做回环是因为当所有等待线程都被释放以后,CyclicBarrier可以被重用。我们暂且把这个状态就叫做barrier,当调用await()方法之后,线程就处于barrier了。

CyclicBarrier类位于java.util.concurrent包下,CyclicBarrier提供2个构造器:

public CyclicBarrier(int parties, Runnable barrierAction) {} public CyclicBarrier(int parties) {}

参数parties指让多少个线程或者任务等待至barrier状态;参数barrierAction为当这些线程都达到barrier状态时会执行的内容。

然后CyclicBarrier中最重要的方法就是await方法,它有2个重载版本:

//用来挂起当前线程,直至所有线程都到达barrier状态再同时执行后续任务public int await() throws InterruptedException, BrokenBarrierException {  };//让这些线程等待至一定的时间,如果还有线程没有到达barrier状态就直接让到达barrier的线程执行后续任务public int await(long timeout, TimeUnit unit)throws InterruptedException,BrokenBarrierException,TimeoutException { };

Demo:

package com.zxd.concurrent.learning;import java.util.concurrent.CyclicBarrier;/** * @Project ConcurrentLearning * @Package com.zxd.concurrent.learning * @Author:zouxiaodong * @Description: * @Date:Created in 17:41 2018/3/21. */public class CyclicBarrierTest {    public static void main(String[] args) throws InterruptedException {        int i = 4;//        CyclicBarrier cyclicBarrier = new CyclicBarrier(i);        CyclicBarrier cyclicBarrier = new CyclicBarrier(i, new Runnable() {            @Override            public void run() {                System.out.println("当前线程号为:"+Thread.currentThread().getName()+",所有线程已到达barrier.................");            }        });        for(int m=0;m
CyclicBarrier

运行结果:


 

Semaphore用法

Semaphore翻译成字面意思为信号量Semaphore可以控同时访问的线程个数,通过 acquire() 获取一个许可,如果没有就等待,而 release() 释放一个许可。

Semaphore类位于java.util.concurrent包下,它提供了2个构造器:

public Semaphore(int permits) {          //参数permits表示许可数目,即同时可以允许多少线程进行访问    sync = new NonfairSync(permits);}public Semaphore(int permits, boolean fair) {    //这个多了一个参数fair表示是否是公平的,即等待时间越久的越先获取许可    sync = (fair)? new FairSync(permits) : new NonfairSync(permits);}

下面说一下Semaphore类中比较重要的几个方法,首先是acquire()release()方法:

public void acquire() throws InterruptedException {  }     //获取一个许可public void acquire(int permits) throws InterruptedException { }    //获取permits个许可public void release() { }          //释放一个许可public void release(int permits) { }    //释放permits个许可

acquire()用来获取一个许可,若无许可能够获得,则会一直等待,直到获得许可。

release()用来释放许可。注意,在释放许可之前,必须先获获得许可。

这4个方法都会被阻塞,如果想立即得到执行结果,可以使用下面几个方法:

public boolean tryAcquire() { };    //尝试获取一个许可,若获取成功,则立即返回true,若获取失败,则立即返回falsepublic boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException { };  //尝试获取一个许可,若在指定的时间内获取成功,则立即返回true,否则则立即返回falsepublic boolean tryAcquire(int permits) { }; //尝试获取permits个许可,若获取成功,则立即返回true,若获取失败,则立即返回falsepublic boolean tryAcquire(int permits, long timeout, TimeUnit unit) throws InterruptedException { }; //尝试获取permits个许可,若在指定的时间内获取成功,则立即返回true,否则则立即返回false

可以通过availablePermits()方法得到可用的许可数目.

Demo:

package com.zxd.concurrent.learning;import java.util.concurrent.Semaphore;/** * @Project ConcurrentLearning * @Package com.zxd.concurrent.learning * @Author:zouxiaodong * @Description: * @Date:Created in 18:13 2018/3/21. */public class SemaphoreTest {    public static void main(String[] args){        int person = 8;        Semaphore semaphore = new Semaphore(5);        for(int i = 0;i < person;i++){            new Thread(new Person(person,semaphore)).start();        }    }    static class Person implements Runnable{        private int num;        private Semaphore semaphore;        public Person(int num, Semaphore semaphore) {            this.num = num;            this.semaphore = semaphore;        }        @Override        public void run() {            try {                System.out.println("1.线程:"+Thread.currentThread().getName()+"准备获取许可,可用semaphore数:"+semaphore.availablePermits());                semaphore.acquire();                System.out.println("2.线程:"+Thread.currentThread().getName()+"占用一个许可,可用semaphore数:"+semaphore.availablePermits());                Thread.sleep(2000);                semaphore.release();                System.out.println("3.线程:"+Thread.currentThread().getName()+"释放一个许可,可用semaphore数:"+semaphore.availablePermits());            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}
Semaphore

运行结果:

转载于:https://www.cnblogs.com/Java-Script/p/11090485.html

你可能感兴趣的文章
jQuery (二)
查看>>
超简单!pytorch入门教程(三):构造一个小型CNN
查看>>
关于JVM的Thin Lock, Fat Lock, SPIN Lock与Tasuki Lock
查看>>
郁闷,垃圾CSS!
查看>>
hdu 1686 Oulipo KMP匹配次数统计
查看>>
OC成员变量和点语法 的访问
查看>>
报文首部
查看>>
创建、使用、删除数据库
查看>>
BackBox错误,无法获得锁...资源暂时不可用...无法锁定管理目录
查看>>
MySql的前戏
查看>>
翻转单词顺序列,如“student. a am I”,返回的的句子应该是“I am a student.”。
查看>>
XStream
查看>>
vtable
查看>>
《Dot Net Book Zero》学习笔记之第五章关键知识点
查看>>
Oracle 存储过程返回结果集|转|
查看>>
Uva(10034)
查看>>
利用redis完成自动补全搜索功能(三)
查看>>
CentOS 6、7 安装 Golang
查看>>
彻底理解正向代理、反向代理、透明代理
查看>>
不懂这些高并发分布式架构、分布式系统的数据一致性解决方案,你如何能找到高新互联网工作呢?强势解析eBay BASE模式、去哪儿及蘑菇街分布式架构...
查看>>