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

有一个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的速度不如前面两个方法快。


mountisome
3 声望1 粉丝