1.多线程
for 循环采用串行方式,会消耗很长时间
多线程可以使 for 循环并行执行,节约时间
final CountDownLatch latch= new CountDownLatch(times);
times 为循环次数也是创建的线程数
for (int i = 0; i < times; i++) {
final int j = i;
Thread thread = new Thread(new Runnable() {
@Override
public void run()
{
写入循环体
latch.countDown();
}
});
thread.start();
}
try {
latch.await(); 等待子线程结束
}
catch (InterruptedException e) {
e.printStackTrace();
}
2.线程池
ExecutorService es = Executors.newFixedThreadPool(1000);
指定线程池有1000个线程,根据需要指定
for (String project : cloudEyeAlarmMap.keySet()) {
es.execute(new Runnable() {
@Override
public void run()
{
写入循环体
}
});
}
try {
es.shutdown();
es.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
一直等待子线程结束
}
catch (InterruptedException e) {
e.printStackTrace();
}