Java Shutdown thread

Source: Internet
Author: User

 Public classThreadservice {PrivateThread Executethread; Private BooleanFinished =false;  Public voidExecute (Runnable Task) {Executethread=NewThread () {@Override Public voidrun () {Thread runner=NewThread (Task); Runner.setdaemon (true);                Runner.start (); Try{runner.join (); Finished=true; } Catch(interruptedexception e) {System.out.println ("Intrupted finished"); //e.printstacktrace ();                }            }        };    Executethread.start (); }     Public voidShutdownLongMills) {        LongCurrentTime =System.currenttimemillis ();  while(!finished) {            LongCost= (System.currenttimemillis ()-currenttime);            System.out.println (cost); if(cost>=Mills) {System.out.println ("Timeout!!!");                Executethread.interrupt ();  Break; }            Try{executethread.sleep (1); } Catch(interruptedexception e) {System.out.println ("Execute is intrupeted");  Break; }} finished=false; }}

Enable the daemon thread to shut down automatically by turning off the main thread

When a child thread runs at the end of a join, it notifies the main thread that it is done, and lets the child thread exit automatically by ending the interrupt thread, which resolves the problem that cannot be ended in the thread block.

 Public classThreadcloseforce { Public Static voidMain (string[] args) {Threadservice service=NewThreadservice (); Longstart=System.currenttimemillis (); Service.execute (()-{            //Read Data            Try{Thread.Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace ();        }        }); Service.shutdown (10000); LongEnd=System.currenttimemillis (); System.out.println (End-start); }}

Java Shutdown thread

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.