Thread interrupted method of Java learning note

Source: Internet
Author: User
Tags thread class

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.