for循环多线程执行_多线程解决for循环效率问题减少执行时间
在for里面,如果执行一次for里面的内容所需时间比较长,可以使用线程池来提高for循环的效率;public class TreadFor {private static final int loopNum = 1*10;public static void main(String args[]) throws InterruptedException {TreadFo...

在for里面,如果执行一次for里面的内容所需时间比较长,可以使用线程池来提高for循环的效率;
public class TreadFor {
private static final int loopNum = 1*10;
public static void main(String args[]) throws InterruptedException {
TreadFor TestThreadPool = new TreadFor();
long bt = System.currentTimeMillis();
List<String> list = new ArrayList<>();
list.add("0");
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
list.add("8");
list.add("9");
TestThreadPool.m1(list);
long et2 = System.currentTimeMillis();
System.out.println("[1]耗时:"+(et2 - bt)+ "ms");
Thread thread = new Thread();
long at = System.currentTimeMillis();
TestThreadPool.m2();
long et3 = System.currentTimeMillis();
System.out.println("[2]耗时:"+(et3 - at)+ "ms");
}
public void m1( List<String> list) {
ExecutorService pool = Executors.newCachedThreadPool();
for (int i = 0; i < list.size(); i++) {
String str = list.get(i);
System.out.println(list.get(i));
Runnable run = new Runnable() {
public void run() {
try {
new Thread().sleep(1000);
//模拟耗时操作
System.out.println("[1]" + Thread.currentThread().getName()+"----"+str);
} catch (Exception e) {
}
}
};
pool.execute(run);
}
System.out.println("[1] done!");
pool.shutdown();
}
public void m2() {
AtomicInteger connectionIds = new AtomicInteger(0);
for (int index = 0; index < loopNum; index++) {
try {
new Thread().sleep(1000); //模拟耗时操作
System.out.println("[2]" + Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("[2] done!");
}
}
由打印结果可知:m1方法是用到了多线程的,多线程此时被线程池管理;而m2方法始终是main主线程执行的。
采用先把要执行的“耗时”内容放到一个线程的执行主体(run方法)里面,再用线程池执行该线程,可大大减少for循环的耗时。但这种情况不适合for次数较大的情形,因为每循环一次,就开辟一个线程,开销较大。注意这种不叫高并发,只是相当于原来由一个工人干的活现在由多个工人协作完成一样。

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)