JUC 即 java.util.concurrent 包,提供了大量的工具类来简化并发编程。
Countdownlatch 门闩(shuan),是一种线程同步器,基于AQS,用于多个线程集结。
1 用法示例一
线程都去处理任务,当任务都做完的时候通知主线程。
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch1 = new CountDownLatch(10);
Thread[] threads = new Thread[10];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
System.out.println(Thread.currentThread().getName()+":处理任务1");
latch1.countDown();
});
}
for (Thread t : threads) {
t.start();
}
latch1.await();
System.out.println("所有任务 都被处理完毕");
}
}
2. Thread.Join方法也可以达到类似效果
线程的join方法也能够实现这样的效果。
public class JoinTest {
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[10];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
System.out.println(Thread.currentThread().getName() + ":处理任务1");
});
}
for (Thread t : threads) {
t.start();
}
//全部集结后再出发
for (Thread t : threads) {
t.join();
}
System.out.println("所有任务 都被处理完毕");
}
}
3. Countdownlatch具有更强大的功能,示例二
假设线程需要做两个任务,在任务1都完成时,放下门闩1,在任务2时,放下门闩2
public class CountDownLatchTest0 {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch1 = new CountDownLatch(10);
CountDownLatch latch2 = new CountDownLatch(10);
Thread[] threads = new Thread[10];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
System.out.println("处理任务1");
latch1.countDown();
//后续任务耗时比较久
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("处理任务2");
latch2.countDown();
});
}
for (Thread t : threads) {
t.start();
}
latch1.await();
System.out.println("所有任务1 都被处理完毕");
latch2.await();
System.out.println("所有任务 都被处理完毕");
}
}
总结
Countdownlatch提供了更灵活的线程同步方法,能够在线程完成后进行集结,且可以设置多个状态标志,使得程序更灵活。
多线程系列在github上有一个开源项目,主要是本系列博客的实验代码。
https://github.com/forestnlp/concurrentlab
如果您对软件开发、机器学习、深度学习有兴趣请关注本博客,将持续推出Java、软件架构、深度学习相关专栏。
您的支持是对我最大的鼓励。