Java Reference
In-Depth Information
If you call the stopThread() method while this thread is blocked on the method call someBlockingMethodCall() ,
this thread will not stop until it returns from the blocked method call or it is interrupted. To overcome this problem,
you need to change the strategy for how to stop a thread. It is a good idea to rely on the interruption technique of a
thread to stop it prematurely. The stopThread() method can be changed to
public void stopThread() {
// interrupt this thread
this.interrupt();
}
In addition, the while-loop inside the run() method should be modified to check if the thread is interrupted.
You need to modify the exception handling code to exit the loop if this thread is interrupted while it is blocked.
The following snippet of code illustrates this logic:
public void run() {
while (Thread.currentThread().isInterrupted())) {
try {
// Do the processing
}
catch (InterruptedException e) {
// Stop the thread by exiting the loop
break;
}
}
}
Handling an Uncaught Exception in a Thread
You can handle an uncaught exception thrown in your thread. It is handled using an object of a class that implements
the java.lang.Thread.UncaughtExceptionHandler interface. The interface is defined as a nested static interface
in the Thread class. It has the following one method defined, where t is the thread object reference that throws the
exception and e is the uncaught exception thrown:
void uncaughtException(Thread t, Throwable e);
Listing 6-26 has the code for a class whose object can be used as an uncaught exception handler for a thread.
Listing 6-26. An Uncaught Exception Handler for a Thread
// CatchAllThreadExceptionHandler.java
package com.jdojo.threads;
public class CatchAllThreadExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
System.out.println("Caught Exception from Thread:" + t.getName());
}
}
 
Search WWH ::




Custom Search