Is (it) synchronized that the current thread object received its own lock?

Consider the following code snippet -

class MyThread extends Thread { private int x = 5; public void run() { synchronized (this) // <-- what does it mean? { for (int i = 0; i < x; i++) { System.out.println(i); } notify(); } } } class Test { public static void main(String[] args) { MyThread m = new MyThread(); m.start(); synchronized (m) { try { m.wait(); } catch (InterruptedException e) { } } } } 

In the above example, does Thread m really get the lock on itself?

+4
source share
3 answers

The current thread receives a lock on the corresponding instance of the MyThread class.

synchronized(this) locks the same object as synchronized(m) in main() .

Finally,

 public void run() { synchronized (this) { 

exactly equivalent

 public synchronized void run() { 
+5
source

Yes, that’s exactly what it means. The thread gets a lock on the instance of the class (MyThread).

+1
source

You should see this like any other java object. what you typed means that other threads cannot access this java object (regardless if it was an instance of the thread or not, because it does not matter.

0
source

All Articles