java并发编程的艺术-读书笔记-01

第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测上下文切换次数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值