读书频道 > 网站 > 网页设计 > Java并发编程的艺术
1.1.1 多线程一定快吗
15-08-26    下载编辑
收藏    我要投稿   

本文所属图书 > Java并发编程的艺术

并发编程领域的扛鼎之作,作者是阿里和1号店的资深Java技术专家,对并发编程有非常深入的研究,《Java并发编程的艺术》是他们多年一线开发经验的结晶。本书的部分内容在出版早期发表在Java并发编程网和InfoQ等技立即去当当网订购
下面的代码演示串行和并发执行并累加操作的时间,请分析:下面的代码并发执行一定比串行执行快吗?
 
public class ConcurrencyTest {

        private static f?inal long count = 10000l;

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

        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--;
                }
                long time = System.currentTimeMillis() - start;
                thread.join();
                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--;
                }
                long time = System.currentTimeMillis() - start;
                System.out.println("serial:" + time+"ms,b="+b+",a="+a);
        }

}

 

 
上述问题的答案是“不一定”,测试结果如表1-1所示。
 
 
从表1-1可以发现,当并发执行累加操作不超过百万次时,速度会比串行执行累加操作要慢。那么,为什么并发执行的速度会比串行慢呢?这是因为线程有创建和上下文切换的
开销。
点击复制链接 与好友分享!回本站首页
分享到: 更多
您对本文章有什么意见或着疑问吗?请到论坛讨论您的关注和建议是我们前行的参考和动力  
上一篇:1.3 功能
下一篇:1.5 小结
相关文章
图文推荐
JavaScript网页动画设
1.9 响应式
1.8 登陆页式
1.7 主题式
排行
热门
文章
下载
读书

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训
版权所有: 红黑联盟--致力于做最好的IT技术学习网站