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