Why is this class not thread safe?

前端 未结 7 1317
误落风尘
误落风尘 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:38

    Others' answers are pretty good explained the reason. I just add something to summarize synchronized:

    public class A {
        public synchronized void fun1() {}
    
        public synchronized void fun2() {}
    
        public void fun3() {}
    
        public static synchronized void fun4() {}
    
        public static void fun5() {}
    }
    
    A a1 = new A();
    

    synchronized on fun1 and fun2 is synchronized on instance object level. synchronized on fun4 is synchronized on class object level. Which means:

    1. When 2 threads call a1.fun1() at same time, latter call will be blocked.
    2. When thread 1 call a1.fun1() and thread 2 call a1.fun2() at same time, latter call will be blocked.
    3. When thread 1 call a1.fun1() and thread 2 call a1.fun3() at same time, no blocking, the 2 methods will be executed at same time.
    4. When thread 1 call A.fun4(), if other threads call A.fun4() or A.fun5() at same time, latter calls will be blocked since synchronized on fun4 is class level.
    5. When thread 1 call A.fun4(), thread 2 call a1.fun1() at same time, no blocking, the 2 methods will be executed at same time.

提交回复
热议问题