0

以下问题是针对 OCP Java SE 7 程序员 II 考试的模拟考试。解决方案说答案是 0,但我和我的同事不确定答案不在 -5 和 5 之间(这是一个选择) 有人可以为我们澄清一下吗?这是代码:

import java.util.concurrent.atomic.AtomicInteger;
class AtomicVariableTest {
        private static AtomicInteger counter = new AtomicInteger(0);
        static class Decrementer extends Thread {
                public void run() {
                        counter.decrementAndGet(); // #1
                }
         }
        static class Incrementer extends Thread {
                public void run() {
                        counter.incrementAndGet(); // #2
                }
         }
        public static void main(String []args) {
                for(int i = 0; i < 5; i++) {
                        new Incrementer().start();
                        new Decrementer().start();
                }
                System.out.println(counter);
         }
}

谢谢!

4

1 回答 1

0

使用一些日志多次运行它表明线程运行的顺序会改变结果。在多次运行中,我确实得到了 0,但实验结果在我的机器上从 -1 到 2 不等。我会说,对此唯一有效的答案是:介于 -5 和 5 之间。

class AtomicVariableTest
{
    private static AtomicInteger counter = new AtomicInteger(0);

    static class Decrementer extends Thread
    {
        public void run()
        {
            counter.decrementAndGet(); // #1
            System.out.println("dec");
        }
    }

    static class Incrementer extends Thread
    {
        public void run()
        {
            counter.incrementAndGet(); // #2
            System.out.println("inc");
        }
    }

    public static void main(String[] args)
    {
        for (int i = 0; i < 5; i++)
        {
            new Incrementer().start();
            new Decrementer().start();
        }
        System.out.println(counter);
    }
}

该程序的输出如下所示:

inc
dec
inc
dec
inc
dec
inc
dec
0
inc
dec

dec
-1
inc
dec
inc
dec
dec
dec
inc
inc
inc
于 2017-05-19T11:31:33.540 回答