互斥量

一下是Java编程思想中的一段代码

public class MultiLock {


public synchronized void f1(int count){
if(count-- > 0){
System.out.println("f1() calling f2() with count " + count);
f2(count);
}
}

public synchronized void f2(int count){
if(count-- >0){
System.out.println("f2() calling f1() with count " + count);
f1(count);
}
}

public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
final MultiLock multiLock = new MultiLock();
new Thread(){
public void run(){
multiLock.f1(10);
}
}.start();
}


}

results:

f1() calling f2() with count 9
f2() calling f1() with count 8
f1() calling f2() with count 7
f2() calling f1() with count 6
f1() calling f2() with count 5
f2() calling f1() with count 4
f1() calling f2() with count 3
f2() calling f1() with count 2
f1() calling f2() with count 1
f2() calling f1() with count 0

这个例子主要说明了同一个互斥量多次被同一个任务获得。在调用f1的时候,f1要获取MultiLock 对象上的锁,然后在这个任务的f2的调用中它也要试图获取这个对象锁,因为调用这个方法的任务本身已经持有了这个锁,所以这个任务应该能够调用这个对象中其它的同步方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值