在Java多线程中使用synced关键字时,没有得到预期的结果

问题描述

我有两个文件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;
        }
    }
}

在这里,我尝试从threads main创建两个thread,并从两个variable都将对此进行操作的线程中访问一个公用threads共同的variable

我正在尝试创建用于实现synchronized关键字的演示。

在我的示例中,在Runner.java-

我使用Runner classchild将{{1}设为Thread extends类的keyword }} overriding

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

有两个count,都使用static methods-synchronizedkeyword,它们分别将count的值增加或减少1。 / p>

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

因此for loop的最终值应为0。

decrement()中-

我正在创建两个count-App.javathreads,它们分别是thread1的实例,并分别传递thread2 Runner class 1和2。

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

现在,我正在打印threads的值。该值应为0。但事实并非如此。在每次执行中,它接近0,但不接近0。

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

解决方法

busyness是静态的,意味着只有一个这样的变量。 countincrement都不是静态的,这意味着它们在decrement上是同步的-这是两个单独的this实例。

将这些方法设为静态:

Runner

或使用显式互斥对象:

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

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