zoukankan      html  css  js  c++  java
  • 在一个主线程中,要求有大量子线程执行完之后,主线程才执行完成?多种方式,考虑效率。

    1、在主函数中使用join()方法

        t1.start();
        t2.start();
        t3.start();
    
        t1.join();//不会导致t1和t2和t3的顺序执行
        t2.join();
        t3.join();
    System.out.println("Main finished");

    2、CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。

    public class WithLatch{
        public static void main(String[] args){
            CountDownLatch latch = new CountDownLatch(3);
            for(int i=0;i<3;i++){
                new ChildThread(i,latch).start();
            }
            try{
                latch.await();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("Main finished");
        }
        static calss ChildThread extends Thread{
            private int id = -1;
            private CountDownLatch latch = null;
    
            public ChildThread(int id, CountDownLatch latch){
                this.id = id;
                this.latch = latch;
            }
            public void run(){
                try{
                    Thread.sleep(Math.abs(new Random().nextInt(5000)));
                    System.out.println(String.format("Child Thread %d finished",id));
                }catch(InterruptedExcepion e){
                    e.printStackTrace();
                }finally{
                    latch.countDown();
                }
            }
        }
    }

    3、使用线程池

    public class WithExecutor{
        public static void main(String[] args) throws InterruptedExcepion{
            ExecutorService pool = Executors.newFixedThreadPool(3);
            List<Callable<Void>> list = new ArrayList<Callable<Void>>();
            for(int i=0;i<3;i++){
                list.add(new ChildThread(i));
            }
            try{
                pool.invokeAll(list);
            }finally{
                pool.shutdown();
            }
            System.out.println("Main finished");
        }
    
        static class ChildThread implements Callable<Void>{
            private int id =  -1;
        
            public ChildThread (int id){
                this.id = id;
            }
            public Void call() throws Exception{
                try{
                    Thread.sleep(Math.abs(new Random().nextInt(5000)));
                    System.out.println(String.format("Child Thread %d finished",id));
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
                return null;
            }
        }
    }
  • 相关阅读:
    百度地图API地理位置和坐标转换
    WebClient 通过get和post请求api
    C#模拟POST提交表单(二)--HttpWebRequest以及HttpWebResponse
    C#模拟POST提交表单(一)--WebClient
    百度外卖接口调试 C#版
    DWZ(JUI) 教程 跨域请求 iframeNavTab
    订餐系统之同步美团商家订单
    订餐系统之同步饿了么商家订单
    外卖订单爬虫(美团,饿了么,百度外卖)
    订餐系统之获取淘宝外卖订单
  • 原文地址:https://www.cnblogs.com/HuiH/p/12733909.html
Copyright © 2011-2022 走看看