Java主线程等待子线程执行完毕-CountDownLatch

本文介绍了一种使用CountDownLatch类来统计并等待多线程执行完毕的方法,通过创建子线程并在主线程中使用CountDownLatch确保所有线程执行结束后再继续执行后续任务。

想做的一个程序如题,主要是想统计子线程都执行完毕所用的时间,网上搜索到了CountDownLatch这个类,这个工具类可以理解为计数器。在这里用于表示正在运行的线程数,当一个子线程结束的时候,将这个计数器减一,最后在主线程的一个地方等待子线程全部执行完毕,再继续运行等待后面的程序。写了个Demo程序,如下:

?
子线程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//子线程
public class SubThread extends Thread{
//子线程记数器,记载着运行的线程数
private CountDownLatch runningThreadNum;
public SubThread(CountDownLatch runningThreadNum){
this .runningThreadNum = runningThreadNum;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+ "-start" );
System.out.println(Thread.currentThread().getName()+ "-do something" );
System.out.println(Thread.currentThread().getName()+ "-end" );
runningThreadNum.countDown(); //正在运行的线程数减一
}
}
?
主线程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Main主线程
public class MainThread {
public static void main(String[] args) throws InterruptedException {
long startTime = System.currentTimeMillis();
int threadNum = 5 ; //线程数
//定义正在运行的线程数
CountDownLatch runningThreadNum = new CountDownLatch(threadNum);
System.out.println(Thread.currentThread().getName()+ "-start" );
//创建多个子线程
for ( int i = 0 ; i < threadNum; i++) {
new SubThread(runningThreadNum).start();
}
//等待子线程都执行完了再执行主线程剩下的动作
runningThreadNum.await();
System.out.println(Thread.currentThread().getName()+ "-end" );
long endTime = System.currentTimeMillis();
System.out.println( "runningTime:" +(endTime-startTime));
}
}
?
其中一次运行结果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
main-start
Thread- 0 -start
Thread- 0 - do something
Thread- 0 -end
Thread- 1 -start
Thread- 1 - do something
Thread- 1 -end
Thread- 2 -start
Thread- 2 - do something
Thread- 2 -end
Thread- 4 -start
Thread- 3 -start
Thread- 4 - do something
Thread- 3 - do something
Thread- 4 -end
Thread- 3 -end
main-end
runningTime: 16

看到打印的结果,满足我现在的要求。笔记下~~

Java 并发编程中,主线程等待子线程完成执行是常见的需求。以下介绍几种常用的方法实现该功能。 ### 1. 使用 `Thread.join()` `join()` 是 `Thread` 类提供的方法,当调用某个线程的 `join()` 方法时,当前线程会阻塞,直到目标线程执行完毕。 ```java public class Main { public static void main(String[] args) { Thread thread = new Thread(() -> { try { System.out.println("子线程开始执行"); Thread.sleep(2000); // 模拟耗时任务 System.out.println("子线程执行完毕"); } catch (InterruptedException e) { e.printStackTrace(); } }); thread.start(); try { thread.join(); // 主线程等待子线程执行完毕 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("主线程继续执行"); } } ``` ### 2. 使用 `CountDownLatch` `CountDownLatch` 是基于 AQS(AbstractQueuedSynchronizer)实现的一个同步工具类,它可以用来控制多个线程的执行顺序。 ```java import java.util.concurrent.CountDownLatch; public class Main { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Thread thread = new Thread(() -> { try { System.out.println("子线程开始执行"); Thread.sleep(2000); // 模拟耗时任务 System.out.println("子线程执行完毕"); } finally { latch.countDown(); // 减少计数器 } }); thread.start(); latch.await(); // 主线程等待计数器归零 System.out.println("主线程继续执行"); } } ``` ### 3. 使用 `LockSupport.park()` 和 `LockSupport.unpark()` `LockSupport` 提供了低级别的线程阻塞和唤醒操作,可以灵活地控制线程的状态。 ```java import java.util.concurrent.locks.LockSupport; public class Main { public static void main(String[] args) { Thread mainThread = Thread.currentThread(); Thread workerThread = new Thread(() -> { try { System.out.println("子线程开始执行"); Thread.sleep(2000); // 模拟耗时任务 System.out.println("子线程执行完毕"); } catch (InterruptedException e) { e.printStackTrace(); } finally { LockSupport.unpark(mainThread); // 唤醒主线程 } }); workerThread.start(); LockSupport.park(); // 阻塞主线程 System.out.println("主线程继续执行"); } } ``` ### 4. 使用 `Object.wait()` 和 `Object.notify()` 通过对象的 `wait()` 和 `notify()` 方法,可以实现线程间的协作机制。 ```java public class Main { private static final Object lock = new Object(); public static void main(String[] args) { Thread thread = new Thread(() -> { synchronized (lock) { try { System.out.println("子线程开始执行"); Thread.sleep(2000); // 模拟耗时任务 System.out.println("子线程执行完毕"); lock.notify(); // 唤醒主线程 } catch (InterruptedException e) { e.printStackTrace(); } } }); thread.start(); synchronized (lock) { try { lock.wait(); // 主线程等待 } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("主线程继续执行"); } } ``` ### 5. 使用 `ExecutorService` 的 `submit()` 和 `Future.get()` 在线程池场景下,可以通过 `ExecutorService` 提交任务并获取 `Future` 对象,然后调用 `get()` 方法阻塞等待任务完成。 ```java import java.util.concurrent.*; public class Main { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService executorService = Executors.newSingleThreadPool(); Future<?> future = executorService.submit(() -> { try { System.out.println("子线程开始执行"); Thread.sleep(2000); // 模拟耗时任务 System.out.println("子线程执行完毕"); } catch (InterruptedException e) { e.printStackTrace(); } }); future.get(); // 阻塞等待任务完成 executorService.shutdown(); System.out.println("主线程继续执行"); } } ``` ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值