Thread interrupted method:
Interrupted () is a method of the thread class that is used to test whether the current thread has been interrupted.
Public classInterruptThreadextendsthread{@Override Public voidrun () { for(inti = 0; i< 5000000; i++) {System.out.println ("I=" + (i + 1))); } }} Public classThreadrunmain { Public Static voidMain (string[] args) {testinterruptthread (); } Public Static voidTestinterruptthread () {Try{InterruptThread It=NewInterruptThread (); It.start (); Thread.Sleep (1000); It.interrupt (); System.out.println ("First Call:" +thread.interrupted ()); System.out.println ("Second Call:" +thread.interrupted ()); } Catch(interruptedexception e) {System.out.println ("Main Catch"); E.printstacktrace (); } System.out.println ("End!"); }}
Operation Result:
The result of printing from the console is that the returned result is false because the current thread is main and the interrupt is interruptthread, so the main thread is not affected.
Let's look at an example:
Public class Threadrunmain { publicstaticvoid main (string[] args) { Testmaininterruptthread (); } Public Static void Testmaininterruptthread () { thread.currentthread (). interrupt (); System.out.println ("First Call:" + thread.interrupted ()); System.out.println ("Second call:" + thread.interrupted ()); System.out.println ("end!" ); }}
Operation Result:
The same is called thread.interrupted (), but why is the first time the result is true, the second time is false?
Because the interrupted () method has the Purge State feature, the value returned by the second call to interrupted () is false.
Thread interrupted method of Java learning note