多线程一定快吗

下面的代码演示串行和并发执行并累加操作的时间,可以发现:当并发累加次数不超过百万次的时候,速度会比串行执行累加操作的要慢,因为线程有创建和上下文切换的开销。

package com.bingfa;

public class ConcurrencyTest {

    private static final long COUNT = 100001;

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

    /**
     * currentTimeMillis() --> Returns the current time in milliseconds.
     */
    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.print("serial: " + time + "ms, b=" + b + ",a= " + a);
    }

    /**
     * InterruptedException:
     * Thrown when a thread is waiting, sleeping, or otherwise occupied,
     * and the thread is interrupted, either before or during the activity.
     * Occasionally a method may wish to test whether the current thread has been interrupted,
     * and if so, to immediately throw this exception.
     *
     * @throws InterruptedException 
     * 这个异常一般发生在线程中,当一个正在执行的线程被中断时就会出现这个异常
     * 假如有两个线程,第一个线程正在运行,第二个没有运行,这时第二个线程启动运行并要求中断第一个线程,
     * 第一个线程就会出现InterruptedException异常并执行该异常下的语句。
     */
    private static void Concurrency() throws InterruptedException {
        long start = System.currentTimeMillis();
        /* Thread类的构造方法中,需要一个实现了Runnable接口的对象,而new就是生成了个实现Runnable接口的类的一个实例对象。把这个实例作为Thread的参数
         * 接口不能实例化,new Runnable()是一个实现接口Runnable的类的对象,后面的run方法是该类里实现的方法,这是匿名内部类的写法
         */
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                int a = 0;
                for (long i = 0; i < COUNT; i++) {
                    a += 5;
                }
            }
        });
        /* 线程必须要先start,才能join,只有启动了,才能对线程进行操作 */
        thread.start(); // 启动thread线程
        int b = 0;
        for (int i = 0; i < COUNT; i++) {
            b--;
        }
        long time = System.currentTimeMillis() - start;
        /* join的话则是将该线程加入到调用线程(一般为主线程) 等该线程结束后 调用线程才会继续运行 */
        thread.join(); // 邀请thread线程先执行,本线程先暂停执行,等待thread线程执行完后,主线程再接着往下执行
        System.out.println("concurrency : " + time + "ms,b=" + b);

    }
}


结果如下

concurrency : 3ms,b=-100001
serial: 2ms, b=-100001,a= 500005
Process finished with exit code 0

如果把COUNT=1000001
结果:

concurrency : 6ms,b=-1000001
serial: 7ms, b=-1000001,a= 5000005
Process finished with exit code 0

如果COUNT=100000001

concurrency : 233ms,b=-100000001
serial: 595ms, b=-100000001,a= 500000005
Process finished with exit code 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值