I have a very simple code but unable to understand.
public class Test extends Thread {
public synchronized void testPrint() {
System.out.println("I am sleeping..."
+ Thread.currentThread().getName());
try {
Thread.sleep(3000);
System.out.println("I am done sleeping..."
+ Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
Test t = new Test();
t.testPrint();
System.out.println("I am out..." + Thread.currentThread().getName());
}
public static void main(String[] args) {
Test t1 = new Test();
Test t2 = new Test();
t1.start();
t2.start();
}
}
Here is my questions
When two threads executing Test t = new Test()
, does this create two different objects with same name? What happens at this line with multiple threads?
I am getting below result,
I am sleeping...Thread-0
I am sleeping...Thread-1
I am done sleeping...Thread-0
I am out...Thread-0
I am done sleeping...Thread-1
I am out...Thread-1
From the output, It definitely means that there are two objects created, that is why both the threads could enter in the sync method. hope my understanding is correct ? How system maintains these two objects?
new
creates a new object. – Kehr