java synchronized load locked thread reentrant details and instance code

  • 2020-06-07 04:36:33
  • OfStack

java synchronized Load locked - thread reentrant

Example code:


public class ReGetLock implements Runnable {

  @Override
  public void run() {
    get();
  }

  public synchronized void get() {
    System.out.println(Thread.currentThread().getId());
    set();
  }

  public synchronized void set() {
    System.out.println(Thread.currentThread().getId());
  }

  public static void main(String[] args) {
    ReGetLock rgl = new ReGetLock();
    new Thread(rgl).start();
  }

}

Can the thread executing the code enter the set method at all?

Since thread rgl first calls the get method and obtains the lock of the ReGetLock object, when thread rgl tries to enter the set method marked with the synchronized keyword, it will be blocked.

In JAVA, when a thread tries to acquire a lock already held by itself, the request succeeds. Otherwise there will be a deadlock.

So, with locking mechanisms like synchronized, threads are reentrant.

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: