OnJava8-Examples/threads/InterruptingIdiom.java

85 lines
2.2 KiB
Java
Raw Normal View History

2016-07-05 14:46:09 -06:00
// threads/InterruptingIdiom.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
// General idiom for interrupting a task
2015-06-15 17:47:35 -07:00
// {Args: 1100}
import java.util.concurrent.*;
class NeedsCleanup {
private final int id;
public NeedsCleanup(int ident) {
id = ident;
2015-11-03 12:00:44 -08:00
System.out.println("NeedsCleanup " + id);
2015-06-15 17:47:35 -07:00
}
public void cleanup() {
2015-11-03 12:00:44 -08:00
System.out.println("Cleaning up " + id);
2015-06-15 17:47:35 -07:00
}
}
class Blocked3 implements Runnable {
private volatile double d = 0.0;
@Override
public void run() {
try {
while(!Thread.interrupted()) {
// point1
NeedsCleanup n1 = new NeedsCleanup(1);
// Start try-finally immediately after definition
// of n1, to guarantee proper cleanup of n1:
try {
2015-11-03 12:00:44 -08:00
System.out.println("Sleeping");
2015-06-15 17:47:35 -07:00
TimeUnit.SECONDS.sleep(1);
// point2
NeedsCleanup n2 = new NeedsCleanup(2);
// Guarantee proper cleanup of n2:
try {
2015-11-03 12:00:44 -08:00
System.out.println("Calculating");
2015-06-15 17:47:35 -07:00
// A time-consuming, non-blocking operation:
for(int i = 1; i < 2500000; i++)
d += (Math.PI + Math.E) / d;
2015-12-02 09:20:27 -08:00
System.out.println(
"Finished time-consuming operation");
2015-06-15 17:47:35 -07:00
} finally {
n2.cleanup();
}
} finally {
n1.cleanup();
}
}
2015-11-03 12:00:44 -08:00
System.out.println("Exiting via while() test");
2015-06-15 17:47:35 -07:00
} catch(InterruptedException e) {
2015-12-02 09:20:27 -08:00
System.out.println(
"Exiting via InterruptedException");
2015-06-15 17:47:35 -07:00
}
}
}
public class InterruptingIdiom {
2016-01-25 18:05:55 -08:00
public static void
main(String[] args) throws Exception {
2015-06-15 17:47:35 -07:00
if(args.length != 1) {
2015-12-02 09:20:27 -08:00
System.out.println(
"usage: java InterruptingIdiom delay-in-mS");
2015-06-15 17:47:35 -07:00
System.exit(1);
}
Thread t = new Thread(new Blocked3());
t.start();
TimeUnit.MILLISECONDS.sleep(new Integer(args[0]));
t.interrupt();
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
NeedsCleanup 1
Sleeping
NeedsCleanup 2
Calculating
Finished time-consuming operation
Cleaning up 2
Cleaning up 1
2015-12-15 11:47:04 -08:00
NeedsCleanup 1
Sleeping
Cleaning up 1
Exiting via InterruptedException
2015-09-07 11:44:36 -06:00
*/