减法计数器,位于 java.util.concurrent 包下,咱们看一下关于它的定义。css
主要方法有:html
首先咱们看一个简单的案例:java
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i < 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"get out");
countDownLatch.countDown();//计数器减1
},String.valueOf(i)).start();
}
//计算器归零,await被唤醒
countDownLatch.await();//等待计数器归零,才向下继续执行
System.out.println("end");
}
}
复制代码
执行结果为:程序员
0get out
1get out
2get out
3get out
5get out
4get out
end
复制代码
来个复杂点的,好比说有这样一个场景:一个大巴司机来接送一群工人去工做,只有当司机到了,工人们才能够出发准备去工做;一样的,只有等工人们都完成工做以后,司机才能接他们回去。转换为代码设计:web
使用两倒计时锁:编程
public class DriverTest {
static final int N = 10;
public static void main(String[] args) throws InterruptedException {
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(N);
for (int i = 0; i < N; ++i){
new Thread(new Worker(startSignal, doneSignal),"工人"+(i+1)+"号").start();
}
doSomethingElse1(); // don't let run yet
startSignal.countDown(); // let all threads proceed
doneSignal.await(); // wait for all to finish
doSomethingElse2();
}
public static void doSomethingElse1() throws InterruptedException {
TimeUnit.SECONDS.sleep(2);
System.out.println("司机来送工人去工做");
}
public static void doSomethingElse2() throws InterruptedException {
TimeUnit.SECONDS.sleep(1);
System.out.println("司机来接工人回去");
}
}
class Worker implements Runnable {
private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
this.startSignal = startSignal;
this.doneSignal = doneSignal;
}
public void run() {
try {
startSignal.await();
doWork();
doneSignal.countDown();
} catch (InterruptedException ex) {} // return;
}
void doWork() throws InterruptedException {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+"开始工做......");
}
}
复制代码
执行结果为:安全
司机来送工人去工做
工人4号开始工做......
工人6号开始工做......
工人8号开始工做......
工人3号开始工做......
工人7号开始工做......
工人9号开始工做......
工人2号开始工做......
工人1号开始工做......
工人10号开始工做......
工人5号开始工做......
司机来接工人回去
复制代码
加法计数器,与 CountDownLatch 做用相反。数据结构
主要方法有:多线程
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println("召唤神龙");
});
for (int i = 0; i < 7; i++) {
final int temp = i+1;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"收集"+temp+"个龙珠");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
复制代码
计数器信号量。并发
如下是个抢车位的案例,假设有6我的去抢3个车位,谁先抢到谁占用,直到离开下一我的再去抢用。
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);
for (int i = 0; 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();
}
}
}
复制代码
semaphore.acquire()
方法表示从该信号量获取许可证,假设已经满了,则等待,直到有许可证被释放。
semaphore.release()
方法表示释放许可证,将其返回到信号量。同时唤醒那些还在等待的线程。
做用:多个共享资源互斥的使用,并发限流,控制最大线程数。
如下是官方文档对于阻塞队列的介绍:
咱们来看一下 BlockingQueue 的接口图:
阻塞队列是一个队列,在数据结构中起的做用以下图:
当队列是空的,从队列中获取元素的操做将会被阻塞。直到其余线程往空的队列插入新的元素。
当队列是满的,从队列中添加元素的操做将会被阻塞。直到其余线程从队列中移除一个或多个元素或者彻底清空,使队列变得空闲起来并后续新增。
在多线程领域:所谓阻塞,在某些状况下会挂起线程(即阻塞),一旦条件知足,被挂起的线程又会自动被唤起。
为何须要 BlockingQueue?
好处是咱们不须要关心何时须要阻塞线程,何时须要唤醒线程,由于这一切BlockingQueue 都给你一手包办了。
在 concurrent 包发布之前,在多线程环境下,咱们每一个程序员都必须本身去控制这些细节,尤为还要兼顾效率和线程安全,而这会给咱们的程序带来不小的复杂度。
经常使用 API
对上述内容的详细解释以下:
咱们对上述内容进行代码展现,首先是抛出异常状况下的插入和移除方法使用:
public class BlockingQueueTest {
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue(3);
//java.lang.IllegalStateException: Queue full
System.out.println(blockingQueue.add("A"));
System.out.println(blockingQueue.add("B"));
System.out.println(blockingQueue.add("C"));
// System.out.println(blockingQueue.add("D")); //此时队列已满,报错 java.lang.IllegalStateException: Queue full
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
// System.out.println(blockingQueue.remove()); //队列已空,报错java.util.NoSuchElementException
}
}
复制代码
返回特殊值
public class BlockingQueueTest {
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue(3);
System.out.println(blockingQueue.offer("A"));
System.out.println(blockingQueue.offer("B"));
System.out.println(blockingQueue.offer("C"));
System.out.println(blockingQueue.offer("D"));//队列已满,插入失败,返回false
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());//队列已空,返回null
}
}
复制代码
一直阻塞
public class BlockingQueueTest {
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue(3);
blockingQueue.put("A");
blockingQueue.put("B");
blockingQueue.put("C");
// blockingQueue.put("D"); //队列已满,会一直阻塞下去
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());//返回正常值
// System.out.println(blockingQueue.take());//队列已空,会一直阻塞
}
}
复制代码
超时等待
public class BlockingQueueTest {
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue(3);
blockingQueue.offer("A");
blockingQueue.offer("B");
blockingQueue.offer("C");
// blockingQueue.offer("D",2, TimeUnit.SECONDS);//队列已满,则等待2s后结束
blockingQueue.poll();
blockingQueue.poll();
blockingQueue.poll();
// blockingQueue.poll(3,TimeUnit.SECONDS); //队列已空,等待3s后结束
}
}
复制代码
同步队列 SynchronousQueue 没有容量。
与其余的 BlockingQueue 不一样,SynchronousQueue 是一个不存储元素的 BlockingQueue 。每个 put 操做必需要等待一个 take 操做,不然不能继续添加元素,反之亦然。
public class SynchronousQueueDemo {
public static void main(String[] args) {
BlockingQueue<String> blockingQueue = new SynchronousQueue<>();//同步队列
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName()+"put 1");
blockingQueue.put("1");
System.out.println(Thread.currentThread().getName()+"put 2");
blockingQueue.put("2");
System.out.println(Thread.currentThread().getName()+"put 3");
blockingQueue.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
}
},"T1").start();
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+"get data:"+blockingQueue.take());
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+"get data:"+blockingQueue.take());
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+"get data:"+blockingQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
},"T2").start();
}
}
复制代码
执行结果为:
T1put 1
T2get data:1
T1put 2
T2get data:2
T1put 3
T2get data:3
复制代码