title: Try to implement a mutex like in java, debugging succeed but run failed
body: <p>I want to implement a mutex in java similar to mutex in C++. So i write a simple class &quot;Mutex&quot;. Here is my code:</p>
  <pre class="lang-java prettyprint-override"><code>public class Mutex implements Lock {
      private boolean locked = false;
  
      //ID of the thread that owns the lock
      long ownerID;
  
      public Mutex() {
  
      }
  
      @Override
      public boolean tryLock() {
          if (locked) {
              //System.out.println(Thread.currentThread().getName() + &quot; lock failed!&quot;);
              return false;
          }
          synchronized (this) {
              if (locked) {
                  return false;
              }
              //System.out.println(Thread.currentThread().getName() + &quot; lock succeed!&quot;);
              ownerID = Thread.currentThread().getId();
              return locked = true;
          }
      }
  
      @Override
      public boolean isLocked() {
          return locked;
      }
  
      @Override
      public void unLock() {
          if (!locked) {
              throw new LockException(&quot;Try to unlock an unlocked lock!&quot;);
          }
          if (Thread.currentThread().getId() != ownerID) {
              throw new LockException(&quot;Thread(ID: &quot; + Thread.currentThread().getId()
                      + &quot;)&quot; + &quot; doesn't match the lock!&quot;);
          }
          //System.out.println(Thread.currentThread().getName() + &quot; unlock!&quot;);
          locked = false;
      }
  }
  </code></pre>
  <p>The results of running and debugging are different. The first thread to grab the lock seems to be able to grab the lock forever. And another thread even cann't run normanlly after the first thread end. The second thread seems to be blocked somwhere? I don't know. Help me please, thank you.</p>