OnJava8-Examples/tasks/Interrupting2.java

54 lines
1.5 KiB
Java
Raw Normal View History

2016-01-25 18:05:55 -08:00
// tasks/Interrupting2.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.
2016-01-25 18:05:55 -08:00
// Interrupting a task blocked with a ReentrantLock
2015-06-15 17:47:35 -07:00
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
class BlockedMutex {
private Lock lock = new ReentrantLock();
public BlockedMutex() {
// Acquire it right away, to demonstrate interruption
// of a task blocked on a ReentrantLock:
lock.lock();
}
public void f() {
try {
// This will never be available to a second task
lock.lockInterruptibly(); // Special call
2015-11-03 12:00:44 -08:00
System.out.println("lock acquired in f()");
2015-06-15 17:47:35 -07:00
} catch(InterruptedException e) {
2015-12-02 09:20:27 -08:00
System.out.println(
"Interrupted from lock acquisition in f()");
2015-06-15 17:47:35 -07:00
}
}
}
class Blocked2 implements Runnable {
BlockedMutex blocked = new BlockedMutex();
@Override
public void run() {
2015-11-03 12:00:44 -08:00
System.out.println("Waiting for f() in BlockedMutex");
2015-06-15 17:47:35 -07:00
blocked.f();
2015-11-03 12:00:44 -08:00
System.out.println("Broken out of blocked call");
2015-06-15 17:47:35 -07:00
}
}
public class Interrupting2 {
2016-01-25 18:05:55 -08:00
public static void
main(String[] args) throws Exception {
2015-06-15 17:47:35 -07:00
Thread t = new Thread(new Blocked2());
t.start();
TimeUnit.SECONDS.sleep(1);
System.out.println("Issuing t.interrupt()");
t.interrupt();
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Waiting for f() in BlockedMutex
Issuing t.interrupt()
Interrupted from lock acquisition in f()
Broken out of blocked call
2015-09-07 11:44:36 -06:00
*/