美文网首页
问题3:(多线程环境)主线程等待所有子线程执行完毕再执行

问题3:(多线程环境)主线程等待所有子线程执行完毕再执行

作者: 一到家就变乖 | 来源:发表于2019-06-10 10:30 被阅读0次

    方法很多,方法1:可以使用线程池的方法,方法2:也可以轻量级的创建多个Thread,再结合CountDownLatch来完成线程统一。先尝试简单有效的 方法2

        //多线程获取ping不同的设备ip
    public List<String> getUnreachedIp(final ArrayList<String> list) {
        final List<String> arrayList = Collections.synchronizedList(new ArrayList<String>());
        
        int ipTotal = list.size();
        int threads = 4;
        final int avg = ipTotal / threads;
        //List<Thread> listThreads = new ArrayList<>();
        final CountDownLatch latch = new CountDownLatch(threads);
        for (int i = 0; i < threads; i++) {
            //4个线程处理ping
            final int count = i;
            new Thread(){
                @Override
                public void run() {
                    for (int j = 0; j < avg; j++) {
                        int number = j + count * avg;
                        if (!PingUtils.isReachIp(list.get(number))) {
                            arrayList.add(list.get(number));
                        }
                    }
                    latch.countDown();
                }
            }.start();
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return arrayList;
    }

    相关文章

      网友评论

          本文标题:问题3:(多线程环境)主线程等待所有子线程执行完毕再执行

          本文链接:https://www.haomeiwen.com/subject/vmpaxctx.html