我在一个类中有 4 个方法(m1
、m2
、m3
和 m4
)。方法 m1
、m2
和 m3
是 synchronized
方法。另外,我分别有 4 个线程 t1
、t2
、t3
和 t4
。
如果t1
访问m1
方法(同步方法),t2
线程可以访问m2
方法(同步方法)同时?如果不是,t2的状态是什么?
最佳答案
If t1 access the m1 method (synchronized method), could t2 thread access m2 method (synchronized method) simultaneously?
synchronized
关键字适用于对象级别,只有一个线程可以持有对象的锁。所以只要你说的是同一个对象,那么no,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
关于java - 两个同步方法是否同时执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3160023/