一道简单的多线程面试题

昨天在网上看到一道面试题,是有关多线程的,我觉得这题挺有意思的,就将它记录了下来。

有一个Long类型的变量,初始值为0,要你用10个线程,每个线程让它自增10000次,最终得到一个100000的值,问你如何实现。

我一开始想,这题不是很简单。我们都知道自增操作是由三条指令构成的:先读取,再加一,最后赋值,那就用synchronized关键字修饰一下自增的方法不就行了吗,或者用concurrent.atomic包下的AtomicLong原子变量的自增方法也可以呀😂。

于是我就写出了如下的代码:

public class Test {

    private static long num = 0;

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    add();
                }
            });
            thread.start();
            System.out.println(thread.getName());
        }
        System.out.println(num);
    }

    public synchronized static void add() {
        num++;
    }

}

可是,当我运行了代码后,却发现结果并不是100000:

Thread-0
Thread-1
Thread-2
Thread-3
Thread-4
Thread-5
Thread-6
Thread-7
Thread-8
Thread-9
8966

这是怎么回事,输出的num值居然不是100000。我一想,是主线程没有等待10个线程完成,而是直接输出了num值🤣。

那么可以使用Thread.join()方法使主线程阻塞,等待线程完成。

public class Test {

    private static long num = 0;

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    add();
                }
            });
            thread.start();
            System.out.println(thread.getName());
            thread.join();
        }
        System.out.println(num);
    }

    public synchronized static void add() {
        num++;
    }

}

现在再来看结果,num值输出是100000了:

Thread-0
Thread-1
Thread-2
Thread-3
Thread-4
Thread-5
Thread-6
Thread-7
Thread-8
Thread-9
100000

其实,删掉方法的synchronized关键字也是一样的结果。

我再用AtomicLong试一下:

public class Test {

    private static final AtomicLong num = new AtomicLong(0);

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    add();
                }
            });
            thread.start();
            System.out.println(thread.getName());
            thread.join();
        }
        System.out.println(num);
    }

    public static void add() {
        num.getAndIncrement();
    }

}

结果也是输出100000:

Thread-0
Thread-1
Thread-2
Thread-3
Thread-4
Thread-5
Thread-6
Thread-7
Thread-8
Thread-9
100000

既然需要让主线程阻塞,等待其他10个线程都完成,我们还可以使用CountDownLatch。每一个线程执行完成之后调用一次countDown()方法,而主线程调用await()方法,就可以实现我们的需求。

public class Test {

    private static long num = 0;

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    add();
                }
                latch.countDown();
            });
            thread.start();
            System.out.println(thread.getName());
        }
        latch.await();
        System.out.println(num);
    }

    public synchronized static void add() {
        num++;
    }

}
Thread-0
Thread-1
Thread-2
Thread-3
Thread-4
Thread-5
Thread-6
Thread-7
Thread-8
Thread-9
100000

经过测试,使用CountDownLatch的速度不如前面两个方法快。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值