To stop a service-based thread
Applications typically create threads that have services, such as a thread pool. These services typically have a longer time to exist than the way they were created, and if the application gracefully exits, the threads of those services also need to end. Because there is no way to quit threading, they need to end on their own.
Sensible encapsulation practices indicate that you should not manipulate a thread one by one to interrupt it, change his priority, and so on ... Unless this is the. Thread owner, the thread API does not have a formal concept of thread ownership. Threads are represented by a thread object and can be freely shared with other objects. However, it makes sense to assume that a thread has one owner. This owner is the class that created the thread. All thread pools have its worker threads, and if necessary interrupt those threads. Then the line pool should be responsible.
For example: Executorservice provides the shutdown and Shutdownnow methods.
For a thread-held service, the lifecycle method should be provided as long as the service exists longer than the method in which the thread was created (lifecycle)
Example: Log service
Public classLogservice {Private FinalBlockingqueue<string>queue; Private FinalLoggerthread Loggerthread; Private FinalPrintWriter writer; Private BooleanIsShutDown; Private intreservations; PublicLogservice (writer writer) { This. Queue =NewLinkedblockingqueue<string>(); This. Loggerthread =NewLoggerthread (); This. writer =NewPrintWriter (writer); } Public voidstart () {Loggerthread.start (); } Public voidStop () {synchronized( This) {IsShutDown=true; } loggerthread.interrupt (); } Public voidLog (String msg)throwsinterruptedexception {synchronized( This) { if(IsShutDown)Throw NewIllegalStateException (/* ... */); ++reservations; } queue.put (msg); } Private classLoggerthreadextendsThread { Public voidrun () {Try { while(true) { Try { synchronized(Logservice. This) { if(IsShutDown && Reservations = = 0) Break; } String msg=Queue.take (); synchronized(Logservice. This) { --reservations; } writer.println (msg); } Catch(Interruptedexception e) {/*Retry*/ } } } finally{writer.close (); } } }}
or use Executorservice
Public classLogService2 {Private FinalExecutorservice Executorservice =executors. Newsinglethreadexecutor (); Private FinalPrintWriter writer; PublicLogService2 (printwriter writer) {Super(); This. writer =writer; } Public voidstart () {} Public voidClose () {Try { This. Executorservice.shutdown (); This. Executorservice.awaittermination (Time_out, UNIT); } finally { if(Writer! =NULL) Writer.close (); } } Public voidlog (String str) { This. Executorservice.execute (NewWriter (str)); }}
Example: Lethal pill
Public classIndexingservice {Private Static Final intcapacity = 1000; Private Static FinalFile POISON =NewFile (""); Private FinalIndexerthread consumer =NewIndexerthread (); Private FinalCrawlerthread producer =NewCrawlerthread (); Private FinalBlockingqueue<file>queue; Private FinalFileFilter FileFilter; Private FinalFile Root; PublicIndexingservice (File root,FinalFileFilter FileFilter) { This. root =Root; This. Queue =NewLinkedblockingqueue<file>(capacity); This. FileFilter =NewFileFilter () { Public BooleanAccept (File f) {returnF.isdirectory () | |filefilter.accept (f); } }; } Private Booleanalreadyindexed (File f) {return false; } classCrawlerthreadextendsThread { Public voidrun () {Try{crawl (root); } Catch(Interruptedexception e) {/*Fall through*/ } finally { while(true) { Try{queue.put (POISON); Break; } Catch(Interruptedexception E1) {/*Retry*/ } } } } Private voidCrawl (File root)throwsinterruptedexception {file[] entries=root.listfiles (FileFilter); if(Entries! =NULL) { for(File entry:entries) {if(Entry.isdirectory ()) crawl (entry); Else if(!alreadyindexed (Entry)) Queue.put (entry); } } } } classIndexerthreadextendsThread { Public voidrun () {Try { while(true) {File file=Queue.take (); if(File = =POISON) Break; Elseindexfile (file); } } Catch(Interruptedexception consumed) {}} Public voidindexfile (file file) {/* ... */ }; } Public voidstart () {Producer.start (); Consumer.start (); } Public voidStop () {producer.interrupt (); } Public voidAwaittermination ()throwsinterruptedexception {consumer.join (); } Public Static voidMain (string[] args) {Indexingservice is=NewIndexingservice (NewFile ("e://"),NewFileFilter () { Public BooleanAccept (File pathname) {System.out.println (pathname); return true; } }); Is.start (); Is.stop (); Try{is.awaittermination (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println ("The End"); }}
Lethal pills can only be used if the production line is known to the consumer thread. The solution in Indexingservice can also be extended to multiple producers, as long as each production line takes a pill into the queue and the consumer thread stops receiving the nth (number of producers) pills.
Example: A service that executes only once
To stop a service-based thread