0
点赞
收藏
分享

微信扫一扫

多线程一定要比单线程快吗

萧萧雨潇潇 2022-04-22 阅读 46
java

多线程一定要比单线程快吗?

1.代码展示

public class ThreadTest {
    /**
     * 问题:多线程一定要比单线程快吗?;
     */
    private static final long count = 100000;

    private static void concurrency() throws InterruptedException {
        long startTime = System.currentTimeMillis();
        Thread thread = new Thread(() -> {
            long a = 0;
            for (long i = 0; i < count; i++) {
                a += 2;
            }
        });
        thread.start();
        int b = 0;
        for (long i = 0; i < count; i++) {
            b++;
        }
        thread.join();
        long time = System.currentTimeMillis() - startTime;
        System.out.println("concurrency thread spend time: " + time);
    }

    private static void singleThread() {
        long startTime = System.currentTimeMillis();
        long a = 0;
        for (long i = 0; i < count; i++) {
            a += 2;
        }
        int b = 0;
        for (long i = 0; i < count; i++) {
            b++;
        }
        long time = System.currentTimeMillis() - startTime;
        System.out.println("single thread spend time: " + time);
    }

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

2.测试数据

countsinglecurrent
10万251
1百万8101
1千万1073
1亿58103
10亿683343

结论:多线程不一定要比单线程要快
原因分析:线程有创建和上下文切换需要花费时间

3.如何减少上下文切换

1.无锁并发编程:多线程竞争锁时,会引起上下文切换,使用一些方法来避免加锁。
2.CAS算法:使用Java中Atomic包
3.使用最少线程:避免大量创建线程,任务很少就不要创建大量线程,会造成大量线程处于等待状态
4.协程:在单线程里实现多任务的调度,并在单线程多个任务间的切换

部分资料参考《Java并发编程的艺术》方腾飞 魏鹏 程晓明

举报

相关推荐

0 条评论