Synchronized method does not work as expected

后端 未结 5 1569
广开言路
广开言路 2020-12-18 09:26

I have a variable which is shared by two threads. The two threads will do some operations on it. I don\'t know why the result of sharedVar is different every time I execute

5条回答
  •  离开以前
    2020-12-18 10:08

    When you use synchronized on non-static method, you use current object as monitor.

    When you use synchronized on static method, you use current object of class (ClassName.class static field) as monitor.

    In your case, you use synchronized on Thread's object (2 different instances), so two different threads will modify your sharedVar static field at same time.

    You can fix it in different ways.

    Move addOne method to Main and make it static.

    private static synchronized void addOne(int times)
    {
        for (int i = 0; i < times; ++i)
        {
            sharedVar++;
        }
    }
    

    Or you can create class called SharedVar with field private int var; and method synchronized void addOne(int times) and pass single instance of SharedVar to your treads.

    public static void main(String[] args) 
    {
        SharedVar var = new SharedVar();
        MyThread mt1 = new MyThread(var);
        MyThread mt2 = new MyThread(var);
        mt1.start();
        mt2.start();
    
        try
        {
            // wait for the threads
            mt1.join();
            mt2.join();
        }
        catch (InterruptedException e1)
        {
            e1.printStackTrace();
        }
    
        System.out.println(var.getVar()); // I expect this value to be 20000, but it's not
    }
    

    But if you need only one integer to be changed in multiple threads, you can use classes from java.til.concurrent.*, like AtomicLong or AtomicInteger.

提交回复
热议问题