Why is this class not thread safe?

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

    As explained in other answers, your code is not Thread safe since static method increment() locks Class monitor and non-static method decrement() locks Object monitor.

    For this code example, better solution exists without synchronzed keyword usage. You have to use AtomicInteger to achieve Thread safety.

    Thread safe using AtomicInteger:

    import java.util.concurrent.atomic.AtomicInteger;
    
    class ThreadSafeClass extends Thread {
    
        private static AtomicInteger count = new AtomicInteger(0);
    
        public static void increment() {
            count.incrementAndGet();
        }
    
        public static void decrement() {
            count.decrementAndGet();
        }
    
        public static int value() {
            return count.get();
        }
    
    }
    

提交回复
热议问题