【问题标题】:Not getting desired result when using synchronized keyword in Java multithreading在 Java 多线程中使用 synchronized 关键字时没有得到想要的结果
【发布时间】:2020-09-09 21:29:54
【问题描述】:

我有两个文件,App.javaRunner.java

App.java -->

public class App {
    private static Thread thread1 = new Runner(1);
    private static Thread thread2 = new Runner(2);

    public static void main(String[] args) throws InterruptedException {
        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.printf("Count = %d\n", Runner.getCount());
    }
}

Runner.java -->

public class Runner extends Thread {
    private volatile static int count = 0;
    private int option = 0;

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

    private synchronized void decrement() {
        count--;
    }

    public Runner(int option) {
        this.option = option;
    }

    public static int getCount() {
        return count;
    }

    @Override
    public void run() {
        switch (option) {
            case 1:
                for (int i = 1; i <= 10000; i++) {
                    increment();
                }
                break;
            case 2:
                for (int i = 1; i <= 10000; i++) {
                    decrement();
                }
                break;
        }
    }
}

在这里,我试图从mainthread 创建两个threads,并从两个线程访问一个公共variable,其中threads 将同时操纵这个公共variable

我正在尝试为 synchronized 关键字的实现创建一个演示。

在我的例子中,Runner.java -

我正在使用 extends keywordoverriding run() method 在正文中制作 Runner class childThread

接下来,我使用constructor 获取option 并在switch - case block 中运行run() 方法中的相应代码。公共变量为count,即static,初始值为0。

有两个methods,都使用synchronizedkeyword-increment()decrement(),分别将count的值加1和减1。

对于option 1 run() 方法使用for loop 运行increment() 10,000 次。 对于option 2 run() 方法使用for loop 运行decrement() 10,000 次。

因此count的最终值应该是0。

App.java -

我正在创建两个threads - thread1thread2,它们是Runner class 的实例,并分别传递constructor argument 1 和2。

我正在使用thread.start() 运行两个threads 并使用thread.join() 等待两个threads 完成

现在,我正在打印count 的值。该值预计为 0。但事实并非如此。在每次执行中,它都接近于 0,但不是 0。

那么,我哪里出错了以及如何更正我的代码?

【问题讨论】:

    标签: java multithreading synchronized


    【解决方案1】:

    count 是静态的,意味着只有一个这样的变量。 incrementdecrement 都不是静态的,这意味着它们在 this 上同步 - 这是两个独立的 Runner 实例。

    将这些方法设为静态:

    private synchronized static void increment() {
        count++;
    }
    
    private synchronized static void decrement() {
        count--;
    }
    

    或使用显式互斥对象:

    private static int count = 0;
    private static Object mutex = new Object;
    
    private int option = 0;
    
    private void increment() {
        synchronized (mutex) {
            count++;
        }
    }
    
    private void decrement() {
        synchronized (mutex) {
            count--;
        }
    }
    

    【讨论】:

      最近更新 更多