searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

Java多线程——主线程在多线程结束后执行任务

2024-02-20 06:53:26
0
0

背景

主线程在多线程结束后执行任务

关键工具

CountDownLatch 

代码示例

import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {

    public static void main(String args[]) {
           final CountDownLatch latch = new CountDownLatch(10);

           for(int i = 1;i<=10;i++) {
                  Thread t = new Thread(new Sport("sproter"+i, i*1000, latch));
                  t.start();
           }


           try{
                latch.await();  //会一直等到所有线程就绪
                System.out.println("所有都已准备好,可以跑了");
           }catch(InterruptedException ie){
               ie.printStackTrace();
           }

        }

    }

    class Sport implements Runnable{
        private final String name;
        private final int timeToStart;
        private final CountDownLatch latch;

        public Sport(String name, int timeToStart, CountDownLatch latch){
            this.name = name;
            this.timeToStart = timeToStart;
            this.latch = latch;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(timeToStart);
            } catch (InterruptedException ex) {
            }
            System.out.println( name + " 已准备好");
            latch.countDown(); //每次减去1
        }
}
0条评论
0 / 1000