CountDownLatch的用法:开一个线程可以等待其他所有线程完事之后再执行,注意等待的线程数目的大小
示例代码如下:
public class Solution {
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
CountDownLatch latch = new CountDownLatch(2);
Worker w1 = new Worker(latch, "张三");
Worker w2 = new Worker(latch, "李四");
Worker w3 = new Worker(latch, "王二");
ArrayList<Worker> al = new ArrayList<>();
al.add(w1);
al.add(w3);
al.add(w2);
Boss boss = new Boss(latch);
Thread t1 = new Thread(boss);
t1.start();
for (Worker worker : al) {
Thread.sleep(500);
executor.execute(worker);
}
// executor.execute(w1);
// executor.execute(w2);
// executor.execute(w3);
// executor.execute(boss);
executor.shutdown();
}
}
class Worker implements Runnable {
private String name;
private CountDownLatch downLatch;
Worker(CountDownLatch downLatch, String name) {
this.name = name;
this.downLatch = downLatch;
}
@Override
public void run() {
try {
System.out.println(this.name + "正在干活!");
Thread.sleep(1);
System.out.println(Thread.currentThread().getName() + " " + this.name);
// TimeUnit.SECONDS.sleep(new Random().nextInt(10));
} catch (InterruptedException ie) {
}
System.out.println(this.name + "活干完了!");
this.downLatch.countDown();
}
}
class Boss implements Runnable {
private CountDownLatch downLatch;
Boss(CountDownLatch downLatch) {
this.downLatch = downLatch;
}
@Override
public void run() {
System.out.println("老板开始检查了,但是所有人的活没干完");
try {
this.downLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("所有人的活都干完了!,老板可以检查");
}
}
BlockingQueue,阻塞队列:当一个线程试图对一个已经满了的队列进行入队列操作时,它将会被阻塞,除非有另一个线程做了出队列操作;同样,当一个线程试图对一个空队列进行出队列操作时,它将会被阻塞,除非有另一个线程进行了入队列操作。