In a below given programme, when i run executer class, it makes two NoWai threads and these
thread gets the reference of Workspace class.
Workspace class has a synchronized method name doDa(),
My question: why and how two threads are able to access synchronized method doDa() at the same time.
We can confirm this by checking the output i.e.
Message: WorkPlace@923e30 first
Thread name: Thread-1
Message: WorkPlace@923e30 first
Thread name: Thread-0
Message: WorkPlace@923e30 second
Thread name: Thread-1
Message: WorkPlace@923e30 second
Thread name: Thread-0
it shows two threads enter the synchronized method at teh same time.
class NoWai extends Thread{
public NoWai(){
start();
}
public void run(){
WorkPlace.getInstance().doDa();
}
}
class WorkPlace{
private Object lock = new Object();
private WorkPlace(){
}
static WorkPlace work = null;
public static WorkPlace getInstance(){
if(work == null){
work = new WorkPlace();
}
return work;
}
public synchronized void doDa(){
TUtil.print(this.getInstance() + " first");
TUtil.print(this.getInstance() + " second");
}
}
class Executer {
public static void main(
String[] args) throws Exception{
for(int i =0 ; i < 2; i++){
new NoWai();
}
}
}
class TUtil{
static void print(String message){
System.out.println("Message: "+message +
"\nThread name: "+Thread.currentThread().getName() + "\n");
}
}