java中多线程的问题

时间:2016-10-24 00:50:51

标签: java multithreading

我是java编程的新手。当我写一个小的多线程程序时,我遇到了一个问题。 这是我的代码:

package com.elqstux.study;

import java.util.logging.Logger;

class Counter {
    private volatile int value;

    public Counter(int value) {
        this.value = value;
    }

    public void add(int n) {
        synchronized (this) {
            this.value += n;
        }
    }

    public int getValue() {
        synchronized (this) {
            return this.value;
        }
    }
}

class App {
    private static final Logger logger = Logger.getLogger(App.class.getName());
    public static void main(String[] argv) {
        final Counter counter = new Counter(0);
        System.out.println(Thread.currentThread().getName());
        for (int i = 0; i < 10; i++) {
            new Thread("" + i) {
                public void run() {
                    counter.add(1);
                    System.out.println("Thread: " + getName() + " running" + ", value = " + counter.getValue());
                }
            }.start();
        }
        System.out.println(String.valueOf(counter.getValue()));
    }
}

输出结果为:

main
Thread: 0 running, value = 1
Thread: 1 running, value = 2
Thread: 2 running, value = 3
Thread: 3 running, value = 4
Thread: 4 running, value = 5
Thread: 5 running, value = 6
Thread: 6 running, value = 7
Thread: 7 running, value = 8
8
Thread: 9 running, value = 9
Thread: 8 running, value = 10

问题是关于System.out.println(String.valueOf(counter.getValue()));,输出8,我认为正确的值应该是10。谁能告诉我原因?

0 个答案:

没有答案