参考
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 }
运行结果:
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
运行结果:
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()
方法得到可用的许可数目.
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(); } } }}
运行结果: