Why is this class not thread safe?

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

    1. decrement is locking on a different thing to increment so they do not prevent each other from running.
    2. Calling decrement on one instance is locking on a different thing to calling decrement on another instance, but they are affecting the same thing.

    The first means that overlapping calls to increment and decrement could result in a cancel-out (correct), an increment or a decrement.

    The second means that two overlapping calls to decrement on different instances could result in a double decrement (correct) or a single decrement.

提交回复
热议问题