Java before there is an API method can be directly shut down the thread, stop (), because this method is forced to close the thread, sometimes error occurs, and then canceled, there are two main methods available:
1. Add a member variable to the thread when a flag is used. The thread run () method takes turns to check for this variable, and it exits when the variable changes. The code examples are as follows:
public class Stopthread extends Thread { private Boolean _run = true; public void Stopthread (Boolean run) { this._run =!run; } @Override public Void Run () {while (_run) { //Data Processing }} }
2, although the first method can be handled well, but in a blocking thread of the statement is often not handled well, because the thread is blocked, it can not check the member variables, it can not be stopped. For example, a blocking statement involving the socket server.accept (). To use a mechanism that allows the blocking thread to exit the blocked state earlier, use the Thread.Interrupt () method. The Interrupt () method only solves the blockage that runs out of the interruptedexception exception. Interrupt () is not shutting down the blocking thread and unblocking it. The previous example:
public class Blocktask extends Thread { @Override public void Run () { try { sleep (10000); } catch (in Terruptedexception e) { } } public static void Main (string[] args) throws Exception { Blocktask task = new Blocktask (); Task.start (); Thread.Sleep (+); Task.interrupt (); }
3, said above, interrupt () can only solve the interruptedexception blocking thread, then encountered some other IO blocking how to deal with it? This time Java will provide the appropriate way to close blocking. For example, a server may need to wait for a request, or a network application may have to wait for a remote host to respond, which can be used with the socket Close () method.
public class Sockettask extends Thread { private volatile serversocket server; public void Stoptask () { try { if (server!=null) { server.close (); SYSTEM.OUT.PRINTLN ("Close task successed"); } } catch (IOException e) { System.out.println ("Close task failded"); } } @Override public Void Run () { try { server = new ServerSocket (3333); } catch (IOException e) { E . Printstacktrace (); } } public static void Main (string[] args) throws interruptedexception { sockettask task = new Sockettask (); Task.start (); Thread.Sleep (+); Task.stoptask (); }}
Java security methods for shutting down threads