多线程--上下文切换

在开发的过程中,多线程一直很受欢迎,因为它的运行速度比串行要快,但是到底快多少呢?一定快么?下面我们用一段代码来测试下

private static final long count = 100000;

    public static void main(String[] args) throws InterruptedException {
        concurrency();
        serial();
    }

    public static void concurrency() throws InterruptedException{
        long start = System.currentTimeMillis();
        Thread thread = new Thread(new Runnable() {
            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();
        long time = System.currentTimeMillis() - start;
        System.out.println("concurrency : " + time + "ms,b = " + b);
    }

    public static void serial(){
        long start = System.currentTimeMillis();
        int a = 0;
        for(int 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);
    }

我们来看一些执行结果:
当count = 10000时 输出:concurrency : 1ms,b = -10000 serial : 0ms,b = -10000,a = 50000
当count = 100000时 输出:concurrency : 2ms,b = -100000 serial : 3ms,b = -100000,a = 500000
当count = 1000000时 输出:concurrency : 5ms,b = -1000000 serial : 3ms,b = -1000000,a = 5000000
当count = 10000000时 输出:concurrency : 7ms,b = -10000000 serial : 11ms,b = -10000000,a = 50000000
当count = 100000000时 输出:concurrency : 48ms,b = -100000000 serial : 84ms,b = -100000000,a = 500000000

当运算次数越少的时候,串行执行反而比多线程快,为什么会出现这样的情况?多线程为什么会执行的慢呢?

其实CPU在执行多线程的时候时通过给每个线程分配CPU时间段来实现多线程的,时间片时CPU分配给各个线程的时间,因为时间片非常短(一般在几十毫秒),所以CPU通过不停的切换线程执行,才能让我们感觉到多个线程在同时执行。但是CPU在线程之间的切换前要保留上一个线程的状态,同时加载当前线程的状态,在这个操作过程中也就差生了一定的时间消耗。同时没操作一次,也就完成了一次上下文切换。

如何减少上下文切换?
1、无所并发编程。多线程竞争锁才会引起上下文切换,所以多线程处理数据时可以尽量避免使用锁,如不同线程处理不同段的数据
2、使用最少线程。避免创建不必要的线程,避免大量线程处于等待状态
3、协程。在单线程里面实现多任务调度,并维持多任务之间的切换。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值