第1章 并发编程的挑战
1.1 上下文切换
1.1.1 多线程一定快吗?
下面代码并行一定比串行执行的快吗?
public class ConcurrencyTest {
private static final long count = 100001;
public static void main (String[] args) throws InterruptedException {
}
private static void concurrency() throws InterruptedException {
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--;
}
//线程阻塞
thread.join();
liong time = System.currentTimeMillis() - start;
System.out.println("concurrency :" + 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--;
}
liong time = System.currentTimeMillis() - start;
System.out.println("serial :" + time+"ms,b="+b+",a="+a);
}
}
测试结果表明:
循环次数 | 串行执行耗时/ms|并发执行耗时|并发比串行快多少
1亿 | 130 | 77 | 约一倍
1千万 | 18 | 9 | 约一倍
1百万 | 5 | 5 | 差不多
10万 | 4 | 3 | 差不多
1万 | 0 | 1 | 慢
为什么当并发执行累加操作不超过百万次时,数度会比串行慢。这是因为线程有创建和上下文切换的开销。
1.1.2 测试下下问切换次数和时长
*使用Lmbench3测上下文切换时长
*使用vmstat测上下文切换次数