Java Reference
In-Depth Information
A better way to stop a thread is to place a loop in the thread's run() method that ends
when a variable changes in value, as in the following example:
public void run() {
while (okToRun == true) {
// ...
}
}
The okToRun variable could be an instance variable of the thread's class. If it is changed
to false , the loop inside the run() method ends.
Another option you can use to stop a thread is to only loop in the run() method while
the currently running thread has a variable that references it.
In previous examples, a Thread object called runner has been used to hold the current
thread.
A class method, Thread.currentThread() , returns a reference to the current thread (in
other words, the thread in which the object is running).
The following run() method loops as long as runner and currentThread() refer to the
same object:
public void run() {
Thread thisThread = Thread.currentThread();
while (runner == thisThread) {
// ...
}
}
If you use a loop like this, you can stop the thread anywhere in the class with the follow-
ing statement:
runner = null;
Summary
Exceptions, assertions, and threads aid your program's design and robustness.
Exceptions enable you to manage potential errors. By using try , catch , and finally ,
you can protect code that might result in exceptions by handling those exceptions as they
occur.
Handling exceptions is only half the equation; the other half is generating and throwing
exceptions. A throws clause tells a method's users that the method might throw an
exception. It also can be used to pass on an exception from a method call in the body of
your method.
 
Search WWH ::




Custom Search