方法很多为障,
方法1
:可以使用線程池的方法齐莲,方法2
:也可以輕量級(jí)的創(chuàng)建多個(gè)Thread亿鲜,再結(jié)合CountDownLatch來完成線程統(tǒng)一允蜈。先嘗試簡(jiǎn)單有效的方法2
。
//多線程獲取ping不同的設(shè)備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個(gè)線程處理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;
}