互斥量

一下是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的调用中它也要试图获取这个对象锁,因为调用这个方法的任务本身已经持有了这个锁,所以这个任务应该能够调用这个对象中其它的同步方法。

你可能感兴趣的:(thread,编程,exception,String,Class,任务)