并发的目的是为了让程序运行的更快,但是,并不是启动更多的线程就能让程序最大限度的并发执行,下面这个例子就是证明并发一定快吗?
package com.itcorey.Thread;
import java.io.Serializable;
/**
* @Classname concurrentTest
* @Description 多线程一定快吗?
* @Date 2020/5/21 18:32
* @Created by corey
*/
public class concurrentTest {
private static final long count = 10000;
public static void main(String[] args) throws Exception {
//并发
concurrentcy();
//串行
Serial();
}
private static void concurrentcy() throws Exception {
long start = System.currentTimeMillis();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
int a = 0;
for (long i = 0; i < count; i++) {
a += 5;
}
}
});
thread.start();
;
int b = 0;
for (long i = 0; i < count; i++) {
b--;
}
long time = System.currentTimeMillis() - start;
thread.join();
System.out.println("concurrentcy==并发"+time+"ms,b="+b);
}
private static void Serial() {
long start = System.currentTimeMillis();
int a = 0;
for (long i = 0;i< count;i++){
a+=5;
}
int b = 0;
for (long i = 0;i<count;i++){
b--;
}
long time = System.currentTimeMillis() - start;
System.out.println("Serial==串行:"+time+"ms,b"+b+",a="+a);
}
}
首先执行的是1万次:
并发1s 串行0s ----->并发比串行慢
第二次 10万
串行2s 并发9s -----并发比串行慢
第三次 100万
串行4s 并发12s -----并发比串行慢
第四次10000000万数据的时候
串行11s 并发14s -----并发比串行慢
第五次一亿次
串行72s 并发48s ----串行比并发差不多慢一倍
总结一下:当并发执行累加操作不超过百万次的时候,速度比串行化累计操作要慢,当上了亿级数据量后,就会快很多,这是因为线程有创建和上下文切换的开销