java 同时执行两个方法_java – 同时执行两个同步方法

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

synchronized关键字在对象级别上应用,并且只有一个线程可以保存对象的锁。所以只要你谈论同一个对象,然后没有,t2将等待t​​1释放锁进入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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值