CountDownLatch
- 减法计数器
代码测试
package pers.vincent.matrix.subject.callable;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1; i <=6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"AAA");
// 减少计数器,到零 释放所有等待的线程
countDownLatch.countDown();
}).start();
}
// 等待锁存计数器到零 再往下执行
countDownLatch.await();
System.out.println("close door");
}
}
原理:
countDown()
减少锁存器的计数,如果计数达到零,释放所有等待的线程。
await()
导致当前线程等到锁存器计数到零,除非线程是 interrupted 。
CyclicBarrier
- 加法计数器
代码测试
package pers.vincent.matrix.subject.callable;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierTest {
public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
CyclicBarrier cyclicBarrier = new CyclicBarrier(5, ()->{
System.out.println("集合完毕,出征");
});
for (int i = 0; i < 5; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "号集合完毕!");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
Semaphore
代码测试
package pers.vincent.matrix.subject.callable;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphroreTest {
public static void main(String[] args) {
/**
* Semaphore
*
* 作用:线程互斥;并发限流
*
* acquire : 控制线程,如果已经满了,则等待
*
* release : 释放资源
*/
Semaphore semaphore = new Semaphore(3);
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();
}
}, String.valueOf(i)).start();
}
}
}