Author: Builder.com
Wednesday, August 11 2004 12:39 PM
Multi-threading techniques are clearly proposed a series of new challenges for developers. In this article, we will discuss one of these challenges: How to interrupt a running thread. In Java through its built-in thread support, writing multithreaded programs is quite simple. However, multithreading techniques will put forward some columns of the program developers, and if it is not properly processed, it may result in an abnormal behavior, and an error that is difficult to discover. In this article, we will discuss one of these challenges: How to interrupt a running thread. Background interrupt a thread means that before completing its task, stop the working process in progress, that is, a valid abort operation. After the thread is interrupted, it will wait for a new task or to continue the next step will depend on the application. Although it is more simple, you still need to take some measures in advance for the ideal results. Here you must pay some advice on the questions you must pay: First, don't use the thread.stop method. Although it can still stop a running thread, such methods are not safe and have been generally opposed by developers. This may also mean that it may not appear in the future Java version. Another way that does not recommend is Thread.Interrupt. Some people may confuse them with the methods mentioned above. Regardless of its name, this method does not immediately interrupt a running thread (later not), as shown in list a. It creates a thread and attempts to use Thread.Iterrupt to stop this thread. The call to thread.sleep () provides a plenty of time to initialize and end. The thread itself does not do any useful thing. If you run the code in the list A, you can see similar below in the console: Starting Thread ... Thread is Running ... Thread is Running ... Interrupting Thread ... thread IS Running ... Thread is Running ... Thread is running ... stopping application ... Even after calling thread.interrupt (), threads run a period of time.
Real interrupt one thread
The best recommendation for interrupting a thread is to use a shared variable to indicate the thread must abort the current work. The thread must be checked for the variable, especially when processing a longer operation, and then abstains the thread task by an orderly manner. The code B code gives the specific implementation of this technology:
The code in the list B will generate the following output (note how the thread exits in the previous method):
Starting thread ...
Thread is Running ...
Thread is Running ...
Thread is Running ...
Ask thread to stop ...
Thread EXITING Under Request ...
STOPPING APPLICATION ...
Although this method needs to write a certain amount of code, this does not give these threads and clears more troubles on threads as needed, especially the removal thread is absolutely necessary for any multi-threaded application. of. It is only necessary to make sure that the shared variable is declared as a variable, or any access package to the synchronization code block or method is required.
So far now, everything is smooth. But what will happen if the thread is blocked to wait for some events? Of course, if the thread is blocked, it will not check the shared variable, so that it cannot stop. There are many cases, such as when called Object.Wait (), serversocket.accept (), and DataGramsocket.Receive () stunned function. These functions can block threads forever. Even with timeout mechanisms, it may not be feasible, or people can't stand the thread until the timeout state is reached. So a certain mechanism must be used to make the thread to exit the blockade.
Unfortunately, there is no such mechanism here for all situations. However, some specific techniques can be used depending on the specific situation. In the following part, I will give the solution taken for most common situations.
Interrupt a thread through thread.interrupt ()
As shown in the list A, the Thread.Iterrupt () method is not interrupting a running thread. This method is only true that if the thread is blocked, an interrupt signal is thrown, and thus the thread exits the blockade state. More precise, if the thread is blocked in the method Object.wait, thread.join or thread.sleep, it will receive an interruptedException, resulting in ahead of the blocking method in advance.
Therefore, if a thread is blocked in any of the above methods, stopping its correct way to set a shared variable and call an interrupt () method (note that the first set variable is very important). If the thread is not locked, call interrupt () does not matter, otherwise, the thread will get an exception (thread itself must be ready to process this) and then exit the lock state. In either case, the final thread will detect shared variables and terminate. The simple example program of the list C indicates the application of this technology.
Once thread.interrupt () is called in the list C code, the thread will get an exception, so it exits the blockade state and determines it should stop. Run these code will output the result:
Starting thread ...
Thread Running ...
Thread Running ...
Thread Running ...
Ask thread to stop ...
Thread Interrupted ...
Thread EXITING Under Request ...
STOPPING APPLICATION ...
Interrupt I / O operation
But how will the thread be blocked when the I / O operation is executed? I / O can maintain a blockade of a thread in a considerable time, in particular to network communication. For example, a server may wait for a user request, or a web application will wait for the response of the remote host.
If you are using channels - new I / O APIs you can get in Java 1.4 will get a ClosedByInterrupTexception exception. If this is the case, the logical method of processing is different from the same-different-different abnormality that is used in the third example.
However, since new I / O recently released and to be further studied, you may also also provide traditional I / O supplied since Java 1.0. In this case, using thread.interrupt () does not generate any help because the thread will not exit the blockade state. The code in the list D shows this process. Although the interrupt () method is called, the thread still does not exit the blockade.
Fortunately, Java Platform provides a solution in this case: a Close () method of the Socket that locks the lock thread. In this case, if the thread is locked when the I / O operation is performed, the thread will get a socketException exception, which is very similar to the interrupt () method throws an interruptedException. The only place that needs to be reminded is that the reference to the Socket must be available, so the close () method can be called. This also means that the Socket object must also be shared. The list e shows this situation. The logic process of processing is the same as that previously given.
Run list E Middle Code will get the following expected results:
Starting thread ...
Waiting for Connection ...
Ask thread to stop ...
Accept () failed or interrupted ...
Thread EXITING Under Request ...
STOPPING APPLICATION ...
Multithreading is a very powerful tool, but it also brings some column challenges to its own processing. One of them is how to interrupt a running thread. If processed, the difficulty of using these technology interrupt threads will not be greater than the same task to complete the same task using the built-in operation provided by Java Platform.
List A: Interrupt thread through Thread.Iterrupt ()
Class example1 extends thread {
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.Iterrupt ();
Thread.sleep (3000);
System.out.println ("Stopping Application ...");
System.exit (0);
}
Public void run () {
While (true) {
System.out.println ("Thread Is Running ...");
Long Time = system.currenttimemillis ();
While (System.currentTimeMillis () - TIME <1000) {
}
}
}
}
List B: a signal transmitted by the interrupt thread class Example2 extends Thread {volatile boolean stop = false; public static void main (String args []) throws Exception {Example2 thread = new Example2 (); System.out.println ( "Starting thread. .. "); thread.start (); thread.sleep (3000); System.Out.println; thread.stop = true; 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) && (! stop) {}} system.out.println ("Thread Exitation under Request ...");}} list C: () exits via Thread.interrupt lock status class Example3 extends Thread {volatile boolean stop = false; public static void main (String args []) throws Exception {Example3 thread = new Example3 (); System.out.println ( " Starting thread ... "); THR Ead.start (); thread.sleep (3000); system.out.println ("Asking Thread to stop ..."); thread.stop = true; thread.interrupt (); thread.sleep (3000); system .out.println ("stopping application ..."); system.exit (0);} public void run () {while (! stop) {system.out.println ("thread running ..."); TRY {Thread.sleep (1000);} catch (interruptedException e) {system.out.println ("Thread Interrupted ...");}} system.out.println ("Thread EXITING Under Request ...");} } List D: Interrupt I / O operation via thread.interrupt ()
Import java.io. *;
Class Example4 Extends Thread {public static void main (string args []) throws exception {
EXAMPLE4 THREAD = New Example4 ();
System.out.println ("Starting Thread ...");
Thread.start ();
Thread.sleep (3000);
System.out.Println ("Interrupting Thread ...");
Thread.Iterrupt ();
Thread.sleep (3000);
System.out.println ("Stopping Application ...");
System.exit (0);
}
Public void run () {
ServerSocket Socket;
Try {
Socket = New Serversocket (7856);
} catch (ioexception e) {
System.out.Println ("Could Not Create The Socket ...");
Return;
}
While (true) {
System.out.println ("Waiting for Connection ...");
Try {
Socket Sock = Socket.accept ();
} catch (ioexception e) {
System.out.println ("Accept () failed or interrupted ...");
}
}
}
}
List E: I / O failure
Import java.net. *;
Import java.io. *;
Class Example5 Extends Thread {
Volatile Boolean Stop = False;
Volatile Serversocket Socket;
Public static void main (string args []) throws exception {
EXAMPLE5 THREAD = New Example5 ();
System.out.println ("Starting Thread ...");
Thread.start ();
Thread.sleep (3000);
System.out.println ("Asking Thread to stop ...");
Thread.stop = true;
thread.socket.close ();
Thread.sleep (3000);
System.out.println ("Stopping Application ...");
System.exit (0);
}
Public void run () {
Try {
Socket = New Serversocket (7856);
} catch (ioexception e) {
System.out.Println ("Could Not Create The Socket ...");
Return;
}
While (! stop) {
System.out.println ("Waiting for Connection ...");
Try {
Socket Sock = Socket.accept ();
} catch (ioexception e) {
System.out.println ("Accept () failed or interrupted ...");
}
System.out.println ("Thread Exiting Under Request ...");
}
}