并发中的常用辅助类
1.CountDownLatch(倒计时器):
这个不好理解,直接用代码表示比较清楚,就相当于一个倒计时器
public class UtilDemo {
public static void main(String[] args) throws InterruptedException {
//总数是6,会进行倒计时,然后计时完毕会执行什么操作
CountDownLatch count = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName() + "Go out");
//倒计时
count.countDown();//倒计时动作
},String.valueOf(i)).start();
}
count.await();//这里是等待倒计时结束后再执行下面的操作
System.out.println("Close Door");
}
}
2.CountDownLatch(加法计数器):
例子:
public class UtilDemo {
public static void main(String[] args) throws InterruptedException {
CyclicBarrier barrier = new CyclicBarrier(6,()->{
System.out.println("收集任务完成");
});
for (int i = 1; i <= 6; i++) {
final int temp = i;
new Thread(
()->{
System.out.println(Thread.currentThread().getName() + "收集了"+ temp + "个");
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)
).start();
}
}
}
要理解这个,可以看看CyclicBarrier的源码
CyclicBarrier barrier = new CyclicBarrier(6,()->{
System.out.println("收集任务完成");
});
CyclicBarrier的源码表示这里需要两个参数,当然一个参数也是有的,不过为了表示需要计数结束后要执行的动作,可以加上一个线程操作
parties表示计数次数,barrierAction表示结束后的一个线程的操作
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
这是只有一个参数的,见名知意,就是计数结束后没有操作
public CyclicBarrier(int parties) {
this(parties, null);
}
3.Semaphore(限流):
首先看Semaphore类的源码:
下面是比较常用的一个,很明显的一个非公平锁,多线程的情况下,谁的效率高,谁先执行
/**
* Creates a {@code Semaphore} with the given number of
* permits and nonfair fairness setting.
*
* @param permits the initial number of permits available.
* This value may be negative, in which case releases
* must occur before any acquires will be granted.
*/
public Semaphore(int permits) {
sync = new NonfairSync(permits);
}
另一个构造器,也可以指定
public Semaphore(int permits, boolean fair) {
sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}
看Semaphore的使用实例:
public class UtilDemo {
public static void main(String[] args) throws InterruptedException {
//这里参数permits相当于线程数量的限制
Semaphore semaphore = new Semaphore(6);
for (int i = 1; i <= 6; i++) {
new Thread(()->{
try {
//获得,假设已经满了,等待,等待被释放为止.
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "抢到车位");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//释放,将当前的信号覆盖,然后唤醒等待的线程
semaphore.release();//释放
}
}).start();
}
}
}