栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

多线程一定要比单线程快吗? 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并发编程的艺术》方腾飞 魏鹏 程晓明

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/831884.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号