多线程使用的三个工具类:CountDownLatch,CyclicBarrier,Semaphore
CountDownLatch
- 减法计数器
构造方法
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
实现
package toolTest;
import java.util.concurrent.CountDownLatch;
// 减法计数器
// 每执行一个线程 计数-1
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
//当我们执行任务的时候 使用其方法让count减一
CountDownLatch countLatch = new CountDownLatch(6);
for (int i = 0; i < 10; i++) {
final int tmp = i;
new Thread(()-> {
System.out.println(tmp +" "+ Thread.currentThread().getName());
// 里面的count-1
countLatch.countDown();
}).start();
}
// 当count为0的时候 才会向下执行
countLatch.await();
System.out.println("已经执行完了6个线程");
}
}
结果
0 Thread-0
1 Thread-1
4 Thread-4
5 Thread-5
3 Thread-3
2 Thread-2
6 Thread-6
已经执行完了6个线程
9 Thread-9
7 Thread-7
8 Thread-8
Process finished with exit code 0
- 其实当我么把for循环中的i < 10改成 i < 5的时候,所得到的结果就是
0 Thread-0
2 Thread-2
1 Thread-1
3 Thread-3
4 Thread-4
- 打开jconsole查看线程的时候就会发现 卡在了 **countLatch.await();**这一行,一直在等待执行六个线程。
CountDownLatch中的await()方法 一层一层的往下看
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
// 如果arg小于0执行这个方法
doAcquireSharedInterruptibly(arg);
}
//
protected int tryAcquireShared(int arg) {
throw new UnsupportedOperationException();
}
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
// 检查是否中断
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
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);
}
实现
public class CyclicBarrierTest {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(5, () -> {
System.out.println("执行了五个线程,CyclicBarrier出现");
});
for (int i = 0; i < 5; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "执行了");
try {
// 判断是否执行了五个线程
// 每执行一个await
// parties - 1;
// parties为0的时候就会执行barrierAction任务
// parties为0后就不会再往下减 而就是再执行一次barrierAction任务
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
结果
Thread-0执行了
Thread-3执行了
Thread-4执行了
Thread-1执行了
Thread-2执行了
执行了五个线程,CyclicBarrier出现
Process finished with exi code 0
Semaphore
相当于厕所的坑位,出去一个 ,才可以进去一个
构造方法 定义了一个许可证permits
public Semaphore(int permits) {
sync = new NonfairSync(permits);
}
实现
public static void main(String[] args) {
// 三个坑位
Semaphore s = new Semaphore(3);
for (int i = 0; i < 6; i++) {
new Thread(() -> {
try {
// 得到坑位
// 得到许可证
s.acquire();
System.out.println(Thread.currentThread().getName() + "进入厕所");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "离开厕所");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 离开坑位
// 放弃许可证
s.release();
}
}).start();
}
}
结果
Thread-0进入厕所
Thread-1进入厕所
Thread-2进入厕所
Thread-1离开厕所
Thread-0离开厕所
Thread-2离开厕所
Thread-3进入厕所
Thread-4进入厕所
Thread-5进入厕所
Thread-3离开厕所
Thread-5离开厕所
Thread-4离开厕所
Process finished with exit code 0