If t1 access the m1 method (synchronized method), could t2 thread access m2 method (synchronized method) simultaneously?
synchronized关键字在对象级别上应用,并且只有一个线程可以保存对象的锁。所以只要你谈论同一个对象,然后没有,t2将等待t1释放锁进入m1时获取的锁。
然而,线程可以通过调用Object.wait()来释放锁而不从方法返回。
If not, what would be the state of t2 ?
它会紧紧地等待t1释放锁(从方法返回或调用Object.wait())。具体来说,它会在一个BLOCKED state。
Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait.
示例代码:
public class Test {
public synchronized void m1() {
try { Thread.sleep(2000); }
catch (InterruptedException ie) {}
}
public synchronized void m2() {
try { Thread.sleep(2000); }
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(t2.getState());
}
}
输出:
BLOCKED