gpt4 book ai didi

java - 两个同步方法是否同时执行

转载 作者:IT老高 更新时间:2023-10-28 21:00:21 26 4
gpt4 key购买 nike

我在一个类中有 4 个方法(m1m2m3m4)。方法 m1m2m3synchronized 方法。另外,我分别有 4 个线程 t1t2t3t4

如果t1访问m1方法(同步方法),t2线程可以访问m2方法(同步方法)同时?如果不是,t2的状态是什么?

最佳答案

If t1 access the m1 method (synchronized method), could t2 thread access m2 method (synchronized method) simultaneously?

synchronized关键字适用于对象级别,只有一个线程可以持有对象的锁。所以只要你说的是同一个对象,那么not2会等待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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com