Why is this class not thread safe?

前端 未结 7 1311
误落风尘
误落风尘 2021-01-30 09:52
class ThreadSafeClass extends Thread
{
     private static int count = 0;

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

     public          


        
相关标签:
7条回答
  • 2021-01-30 10:42

    You have two synchronized methods, but one of them is static and the other is not. When accessing a synchronized method, based on it's type (static or non-static), a different object will be locked. For a static method, a lock will be put on the Class object, while for the non-static block, a lock will be put on the instance of the class that runs the method. Because you have two different locked objects, you can have two threads that modify the same object simultaneously.

    0 讨论(0)
提交回复
热议问题