The Stop () method has been deprecated because it is not safe. Detailed explanations are given in the API documentation.
Interrupts the thread through the interrupted () method. Not recommended.
Stop the thread by ending the run () method with a shared variable. such as instance
Copy Code code as follows:
public class Threadinterrupt {
public static void Main (String []args) {
Runner run = new Runner ();
Run.start ();
try {
Thread.Sleep (10000);
catch (Interruptedexception e) {
TODO auto-generated Catch block
}
Run.stop ()//obsolete methods, not recommended, too rough
Run.interrupt (); Throws an exception, but it is obviously inappropriate to write a business in exception handling and is not recommended
run.flag=false;//recommended method for stopping a thread
}
}
Class Runner extends thread{
Boolean flag = true;
public void Run () {
/* while (true) {
System.out.println (New Date () + "----");
try {
Sleep (1000);
catch (Interruptedexception e) {
TODO auto-generated Catch block
System.out.println ("interrupted");
Return
}
}
*/
while (flag) {
System.out.println (New Date () + "----");
try {
Sleep (1000);
catch (Interruptedexception e) {
TODO auto-generated Catch block
System.out.println ("interrupted");
Return
}
}
}
}