In earlier versions of Java, a method for terminating a thread was provided: Stop (). In subsequent releases, however, this method was abandoned because its interrupts were "immediate", which could result in inconsistent data. For example, during the transfer process. So in jdk1.5, there is a way to solve this problem: Intertupt (). This method will abort in run (), "interrupting a thread that's not alive need not has any effect.", so there is no data inconsistency. But a lot of people are still having problems with this approach. Here is an example:
public class ThreadTest extends Thread { int count=0; public void Run () { System.out.println (getName () + "will run ..."); while (!this.isinterrupted ()) { System.out.println (getName () + "Running" +count++); try{ Thread.Sleep (+); } catch (Interruptedexception e) { System.out.println (getName () + "exits from blocking ..."); System.out.println ("this.isinterrupted () =" +this.isinterrupted ()); } } System.out.println (GetName () + "already terminated!");} }
public class Threaddemo {public static void Main (String argv[]) throws interruptedexception{ threadtest ta=new ThreadTest (); Ta.setname ("ThreadTest"); Ta.start (); Thread.Sleep (+); System.out.println (Ta.getname () + "will be Interrupted"); Ta.interrupt (); System.out.println ("ta.isinterrupted () =" +ta.isinterrupted ());} }
The following gives the result of the operation:
After the "break" is visible, the program continues to run. Why is it? When you sleep, calling Interupt throws an exception and causes the thread to re-be in a non-disruptive state. The way to fix this bug is to use a flag bit to fix it.
public class ThreadTest extends Thread { private boolean isinterrupted=false; int count=0; public void Interrupt () { isinterrupted = true; Super.interrupt (); } public void Run () { System.out.println (getName () + "will run ..."); while (!isinterrupted) { System.out.println (getName () + "Running" +count++); try{ Thread.Sleep (+); } catch (Interruptedexception e) { System.out.println (getName () + "exits from blocking ..."); System.out.println ("this.isinterrupted () =" +this.isinterrupted ()); } } System.out.println (GetName () + "already terminated!");} }
This will solve the problem above.
Attention:
Calling interrupt is also invalid when the thread reads the large file data again. This time, we can also through the sign, to solve. For example, if the state of the interrupt is detected, we force the closing of the stream by calling the Close method.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
How to terminate a thread in Java