方法很多,
方法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;
}
网友评论