The program is very simple. However, in front of programmers, multithreading presents a new set of challenges that, if not properly addressed, can lead to unexpected behavior and subtle, difficult to detect errors.
In this article, we address one of these challenges: how to break a running thread.
Background break (Interrupt) A thread means stopping everything it is doing before the thread completes its task, effectively aborting its current operation. Whether a thread dies, waits for a new task, or continues to run to the next step depends on the program. Although it may seem simple for the first time, you have to do some early warning to achieve the desired results. You'd better keep in mind the following caveats.
First, forget the Thread.stop method. Although it does stop a running thread, this approach is insecure and unpopular, meaning that it will no longer exist in future Java versions.
Some thoughtless fellow may be thread.interrupt by another method. Although the name seems to imply something, this method does not interrupt a running thread (which will be further explained later), as described in Listing a. It creates a thread and attempts to stop the thread by using the Thread.Interrupt method. The invocation of the Thread.Sleep () method provides ample time for the initialization and abort of the thread. The thread itself is not involved in any useful operation.
Class Example1 extends Thread {
Boolean stop=false;
public static void Main (String args[]) throws Exception {
Example1 thread
= new Example1 ();
SYSTEM.OUT.PRINTLN ("Starting thread ...");
Thread.Start ();
Thread.Sleep (3000);
System.out.println (
"interrupting thread ...");
Thread.Interrupt ();
Thread.Sleep (
3000);
SYSTEM.OUT.PRINTLN ("Stopping application ...");
System.exit (0);
}
public void Run () {
while (!stop) {
System.out.println ("Thread is running ...");
Long time = System.currenttimemillis ();
while ((System.currenttimemillis ()-Time
< 1000)) {
}
}
System.out.println
("Thread exiting under request ...");
}
}