Java Reference
In-Depth Information
27
Thread.sleep(sleepTime); // put thread to sleep
28
}
29
catch (InterruptedException exception)
30
{
31
exception.printStackTrace();
32
Thread.currentThread().interrupt(); // re-interrupt the thread
33
}
34
35
// print task name
36
System.out.printf( "%s done sleeping%n" , taskName);
37
}
38
} // end class PrintTask
Fig. 23.3 | PrintTask class sleeps for a random time from 0 to 5 seconds. (Part 2 of 2.)
A PrintTask executes when a thread calls the PrintTask 's run method. Lines 25-26
display a message indicating the name of the currently executing task and that the task is
going to sleep for sleepTime milliseconds. Line 27 invokes static method sleep of class
Thread to place the thread in the timed waiting state for the specified amount of time. At
this point, the thread loses the processor, and the system allows another thread to execute.
When the thread awakens, it reenters the runnable state. When the PrintTask is assigned
to a processor again, line 36 outputs a message indicating that the task is done sleeping,
then method run terminates. The catch at lines 29-33 is required because method sleep
might throw a checked exception of type InterruptedException if a sleeping thread's
interrupt method is called.
Let the Thread Handle InterruptedException s
It's considered good practice to let the executing thread handle InterruptedException s.
Normally, you'd do this by declaring that method run throws the exception, rather than
catching the exception. However, recall from Chapter 11 that when you override a meth-
od, the throws may contain only the same exception types or a subset of the exception
types declared in the original method's throws clause. Runnable method run does not have
a throws clause in its original declaration, so we cannot provide one in line 21. To ensure
that the executing thread receives the InterruptedException , line 32 first obtains a ref-
erence to the currently executing Thread by calling static method currentThread , then
uses that Thread 's interrupt method to deliver the InterruptedException to the current
thread. 1
Using the ExecutorService to Manage Threads that Execute PrintTask s
Figure 23.4 uses an ExecutorService object to manage threads that execute PrintTasks
(as defined in Fig. 23.3). Lines 11-13 create and name three PrintTask s to execute. Line
18 uses Executors method newCachedThreadPool to obtain an ExecutorService that's
capable of creating new threads as they're needed by the application. These threads are
used by ExecutorService to execute the Runnable s.
1.
For detailed information on handling thread interruptions, see Chapter 7 of Java Concurrency in
Practice by Brian Goetz, et al., Addison-Wesley Professional, 2006.
 
Search WWH ::




Custom Search