Java Reference
In-Depth Information
Finally, you change the run() loop in MsgThread to check the value of time-
ToStop . You exit the run method and stop the thread when that value is true.
public void run () {
// Create a loop that runs till timeToStop.
while (!timeToStop) {
System.out.println ("Inside a thread");
}
System.out.println ("Exit a thread");
}
}
I MPLEMENTING R UNNABLE
One obvious limitation of the first thread-management technique is the fact that
your class has to inherit from the Thread class. What if you need to build a threaded
class, but it must inherit from some other class? In order to support this require-
ment, Java provides another mechanism to create in-process threads.
The second approach is to have your class implement the Runnable interface.
The class that you want to run as a thread needs to define the run() method from
this interface. You also should define a stopThread() method that can be used to
stop your class.
public class MsgThreadRunnable
implements Runnable {
private volatile Boolean timeToStop = false;
public void stop Thread() {
timeToStop = true;
}
public void run () {
// Create a loop that runs till timeToStop.
while (!timeToStop) {
System.out.println ("Inside a thread");
}
System.out.println ("Exit a thread");
}
}
Search WWH ::




Custom Search