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

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

    //多线程获取ping不同的设备ip
public List getUnreachedIp(final ArrayList list) {
    final List arrayList = Collections.synchronizedList(new ArrayList());
    
    int ipTotal = list.size();
    int threads = 4;
    final int avg = ipTotal / threads;
    //List 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:(多线程环境)主线程等待所有子线程执行完毕再执行)