【问题标题】:synchronized method not giving correct result [duplicate]同步方法没有给出正确的结果[重复]
【发布时间】:2018-09-16 19:28:32
【问题描述】:

我已经写了下面提到的代码,我期待 12000 作为答案。但是没有得到正确的答案。每次跑步我都会得到一些新号码

包线程;

public class ThreadExp extends Thread {

    static volatile int count=0;

    public synchronized void increment() {
        count++;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ThreadExp a = new ThreadExp();
        a.start();
        ThreadExp a1 = new ThreadExp();
        a1.start();

        try {
            a.join();
            a1.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println(count);
    }

    public void run() {
        for(int i=1; i<=6000 ;i++) { 
            increment();
        }
    }
}

【问题讨论】:

  • 使用AtomicInteger
  • @ElliottFrisch,如果这个程序按照 OP 认为的那样工作,那么它唯一能做的就是打印出数字 12000。不需要AtomicInteger:全部它需要一行:System.out.println("12000")。但是 OP 的目标不是制作一个打印 12000 的程序,也不是制作一个计数到 12000 的程序。而是要了解 synchronized 做什么和不做什么。显然,这仍在进行中。

标签: java multithreading


【解决方案1】:

非静态同步方法在this 对象上同步(请参阅JLS, §8.4.3.6)。因此,您使用的两个ThreadExp 实例不会执行increment() 互斥。

您可以通过将increment() 定义为static 来解决您的问题,因为静态方法在代表该类型的class-Object 上同步。

Elliott Frisch 提到了另一种解决方案:使用 AtomicInteger 而不是 volatile int

【讨论】:

    猜你喜欢
    • 2016-05-02
    • 2020-10-26
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    相关资源
    最近更新 更多