I was ask in an interview that with respect to multi threading , Suppose you have 2 threads (Thread-1 and Thread-2) on same object. Thread-1 is in synchronized method1(), can Thread-2 enter synchronized method2() at same time in java by any way .
I replied no No, here when Thread-1 is in synchronized method1() it must be holding lock on object’s monitor and will release lock on object’s monitor only when it exits synchronized method1(). So, Thread-2 will have to wait for Thread-1 to release lock on object’s monitor so that it could enter synchronized method2().
but still please advise is there any way by which Thread-2 ,enter synchronized method2() at same time in java by any way is there any hack if to achieve this thing
below is my program , rite now I have changed the implementation now please advise on this as the output of the below program is
inside M1()
t1--->RUNNABLE
inside M2()
t2--->RUNNABLE
below is my updated code
public class Test {
private final Object lockA = new Object();
private final Object lockB = new Object();
public void m1() {
synchronized(lockA) {
try {
System.out.println("inside M1()");
Thread.sleep(100);
}
catch (InterruptedException ie)
{}
}
}
public void m2() {
synchronized(lockB) {
try {
System.out.println("inside M2()");
Thread.sleep(100); }
catch (InterruptedException ie) {}
}
}
public static void main(String[] args) throws InterruptedException {
final Test t = new Test();
Thread t1 = new Thread()
{ public void run() { t.m1(); } };
Thread t2 = new Thread()
{ public void run() { t.m2(); } };
t1.start();
//Thread.sleep(500);
t2.start();
// Thread.sleep(500);
System.out.println("t1--->"+t1.getState());
System.out.println("t2--->"+t2.getState());
}
}