并发编程一定比顺序编程速度更快么?
我们来看下案例
public class ConcurrencyTest {
private static final long count = 10001;
public static void main(String[] args) throws InterruptedException {
serial();//顺序编程
concurrency();//并发编程
}
/**
* 顺序编程
**/
private static void serial() {
long start = System.currentTimeMillis();
int a = 0;
for (int i = 0; i < count; i++) {
a += 5;
}
int b = 0;
for (int i = 0; i < count; i++) {
b--;
}
long time = System.currentTimeMillis() - start;
System.out.println("Serial:" + time + "ms,b=" + b + ",a=" + a);
}
/**
* 并发编程
*/
private static void concurrency() throws InterruptedException {
long start = System.currentTimeMillis();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
int a = 0;
for (int i = 0; i < count; i++) {
a += 5;
}
}
});
thread.start();
int b = 0;
for (int i = 0; i < count; i++) {
b--;
}
long time = System.currentTimeMillis() - start;
thread.join();
System.out.println("Concurrency :" + time + "ms,b=" + b);
}
}
输出结果:
Serial:0ms,b=-10001,a=50005
Concurrency :1ms,b=-10001
该例子测试后可以发现,并发编程比顺序编程速度反而更慢
为什么呢?
- 顺序编程只需要程序执行时间
- 并发编程除了程序执行需要时间,两个线程之间切换也需要时间
因此我们常说:没有阻塞的任务使用多线程就没有意义
本文标题:10. Java并发编程的魅力之并发一定比顺序编程速度更快么?
本文链接:https://blog.quwenai.cn/post/3124.html
版权声明:本文不使用任何协议授权,您可以任何形式自由转载或使用。






还没有评论,来说两句吧...