for循环是我们编程中经常用到的,但是如果每一次循环中耗时较久,那么整个程序就会很慢,甚至超时,下面我就来改进一下这种情况。
public class TestSynchronizedFor {
private static final int num = 10;
public static void main(String args[]) throws InterruptedException {
TestSynchronizedFor testSynchronizedFor = new TestSynchronizedFor();
long at = System.currentTimeMillis();
testSynchronizedFor.start();
long et3 = System.currentTimeMillis();
System.out.println("总耗时:"+(et3 - at)+ "ms");
}
public static void start() {
for (int index = 0; index < num; index++) {
try {
new Thread().sleep(1000); //模拟耗时操作
System.out.println("[2]" + Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("[2] done!");
}
}
执行结果:
[2]main
[2]main
[2]main
[2]main
[2]main
[2]main
[2]main
[2]main
[2]main
[2]main
[2] done!
总耗时:10076ms
我们人为的在让每一次循环中耗时1s,10次循环下来总的时间为10s多一点。这是我们这样没有任何改进的时候,接下来,我们把这段代码改动一下。
public class TestAsynchronousFor {
private static final int num = 10;
public static void main(String args[]) throws InterruptedException {
TestAsynchronousFor testAsynchronousFor = new TestAsynchronousFor();
long bt = System.currentTimeMillis();
testAsynchronousFor.start();
long et3 = System.currentTimeMillis();
System.out.println("伴随线程"+Thread.currentThread().getName()+"正在执行中" );
System.out.println("总耗时:"+(et3 - bt)+ "ms");
}
public static void start() {
ExecutorService pool = Executors.newCachedThreadPool();
for (int i = 0; i < num; i++) {
Runnable run = new Runnable() {
public void run() {
try {
new Thread().sleep(1000);
//模拟耗时操作
System.out.println( Thread.currentThread().getName()+"执行了" );
} catch (Exception e) {
}
}
};
pool.execute(run);
}
pool.shutdown();
while (true) {
if (pool.isTerminated()) {
System.out.println("所有的子线程都结束了!");
break;
}
try {
new Thread().sleep(1000);
} catch (Exception e) {
}
}
}
}
执行结果:
pool-1-thread-1执行了
pool-1-thread-2执行了
pool-1-thread-7执行了
pool-1-thread-6执行了
pool-1-thread-5执行了
pool-1-thread-4执行了
pool-1-thread-3执行了
pool-1-thread-9执行了
pool-1-thread-8执行了
pool-1-thread-10执行了
所有的子线程都结束了!
伴随线程main正在执行中
总耗时:2021ms
两次执行
执行差异 执行用时 运用线程数量
第一次 10076ms 1个(main线程)
第二次 2068ms 11个(10个子线程+1个主线程)
对比 | 执行用时 | 使用线程数量 |
---|---|---|
第一次 | 10076ms | 1个(main线程) |
第二次 | 2068ms | 11个(10个子线程+1个main线程) |
通过比较我们发现第二次的用时大约为2s,时间上是大大的减少了,我们分析一下具体差异。第一次执行是main线程一个线程执行完了10次任务,第二次是10个子线程处理了10次任务,相当于原来1个工人的产量任务分给了10个人协同完成。这种方式虽然减少了for循环的用时,但是这种做法不适用于for次数较大的情况,因为每循环一次就开辟了一个线程,对于程序的开销变大。选用哪种方式还要综合考量我们的业务场景。
商标检索小程序
专利翻译小程序
专利检索小程序