OnJava8-Examples/concurrency/MultiLock.java

44 lines
1.1 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// concurrency/MultiLock.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -07:00
// One thread can reacquire the same lock.
public class MultiLock {
public synchronized void f1(int count) {
if(count-- > 0) {
2015-12-02 09:20:27 -08:00
System.out.println(
"f1() calling f2() with count " + count);
2015-06-15 17:47:35 -07:00
f2(count);
}
}
public synchronized void f2(int count) {
if(count-- > 0) {
2015-12-02 09:20:27 -08:00
System.out.println(
"f2() calling f1() with count " + count);
2015-06-15 17:47:35 -07:00
f1(count);
}
}
public static void main(String[] args) throws Exception {
final MultiLock multiLock = new MultiLock();
new Thread() {
@Override
public void run() {
multiLock.f1(10);
}
}.start();
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
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
2015-09-07 11:44:36 -06:00
*/