Close Executorservice
Executorservice provides two methods of closing, using shutdown to shut down gracefully, and forcibly closing using Shutdownnow. When a forced shutdown occurs, Shutdownnow first closes the currently executing task. The list of all tasks that have not yet started is then returned.
Returns the not started task list this sentence did not understand the way to return, so went to check the source code
/** * Attempts to stop all actively executing tasks, halts the * processing of waiting tasks, and returns a Li St of the tasks * that were awaiting execution. * * <p>this method does not wait for actively executing the tasks to * terminate. Use {@link #awaitTermination awaittermination} to * do. * * <p>there is no guarantees beyond best-effort attempts to stop * processing actively executing tasks. For example, typical * implementations would cancel via {@link thread#interrupt}, so any * task this fails to RESPO nd to interrupts may never terminate. * * @return List of tasks that never commenced execution * @throws SecurityException If a security manager exists and * Shutting down this executorservice could manipulate * threads that the caller are not permitted To modify * because it does no hold {@link * java.lang.runtimepermission}{@code ("Modifythread") }, * Or the security manager ' s {@code checkAccess} method * denies access. */list<runnable> Shutdownnow ();
Returns the runnable of the submit in the form of a list
Or the same as the previous one. Using the log service as chestnuts
Import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.rejectedexecutionexception;import Java.util.concurrent.timeunit;public class LogService { Private final Executorservice exec = Executors.newsinglethreadexecutor ();p rivate final int TIMEOUT = 100;...public void St Art () {}public void Stop () throws Interruptedexception {try {exec.shutdown (); Exec.awaittermination (TIMEOUT, Timeunit.milliseconds);} finally {writer.close ();}} public void log (String msg) {Try{exec.execute (New Writertask (msg)));} catch (Rejectedexecutionexception ignored) {}}}
Part of the code is omitted. As the code in the previous article is the same, the main show is the use of Executorservice after the Stop method modified look
Poison Pill Object
This is another consumer producer of chestnuts, poison pills refers to an object placed on the queue, its role is when the object is obtained, immediately stop. In the FIFO queue, the poison pill object will ensure that the consumer completes all the work in the queue before shutting down.
Give me a chestnut. Oh.. It took a long time to debug well.
Import Java.io.file;import Java.io.filefilter;import Java.util.concurrent.blockingqueue;import Java.util.concurrent.linkedblockingqueue;public class Inderxingservice {private static final file POISON = new file (""); Private final Indexerthread consumer = new Indexerthread ();p rivate final Crawlerthread producer = new Crawlerthread ();p Riv Ate final blockingqueue<file> queue = new linkedblockingqueue<file> ();p rivate final FileFilter filefilter; Private Final File root = new file ("F://desktop/open");p ublic static void Main (string[] args) {Inderxingservice index = NE W inderxingservice (null, NULL); Index.start ();} Public Inderxingservice (FileFilter filefilter, File root) {this.filefilter = FileFilter;} public void Start () {Producer.start (); Consumer.start ();} public void Stop () {producer.interrupt ();} public void Awaittermination () throws Interruptedexception {Consumer.join ();} Class Crawlerthread extends Thread {@Overridepublic void Run () {//TODO auto-generated method Stubtry {Crawl (root);} catch (Interruptedexception e) {e.printstacktrace ();} finally {System.out.println ("Putpoison"); while (true) {try { Queue.put (POISON); break;} catch (Interruptedexception E1) {}}}}private void crawl (file root) throws Interruptedexception {//Add content to file file[] entries = Root.listfiles (); if (entries! = null) {for (File entry:entries) {if (Entry.isdirectory ()) {Crawl (Entry.getabsolutefile ( ));} else if (!alreadindex (entry)) {Queue.put (entry);}}}} Private Boolean Alreadindex (File entry) {//TODO auto-generated method stubif (Queue.contains (entry)) {return true;} return false;}} Class Indexerthread extends Thread {@Overridepublic void run () {while (true) {file File;try {file = Queue.take (); if (file = = POISON) {break;} else {indexfile (file);}} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} private void Indexfile (File root) throws Interruptedexception {System.out.println (Root.getname ());}}}
This is the chestnut that traverses a directory of files-0-
Just tried to traverse the entire F-drive. Looks like the consumer to follow. And there's no pressure to use it.
public static void Main (string[] args) {Inderxingservice index = new Inderxingservice (null, NULL); Index.start (); try {thre Ad.sleep (1000);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Index.stop ();}
Tried the interrupt method.
Upgradereport.xslt
Upgradereport_minus.gif
Upgradereport_plus.gif
Java.lang.InterruptedException
Putpoison
At java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly (Unknown Source)
At java.util.concurrent.locks.ReentrantLock.lockInterruptibly (Unknown Source)
At Java.util.concurrent.LinkedBlockingQueue.put (Unknown Source)
At Inderxingservice$crawlerthread.crawl (inderxingservice.java:73)
At Inderxingservice$crawlerthread.crawl (inderxingservice.java:71)
At Inderxingservice$crawlerthread.crawl (inderxingservice.java:71)
At Inderxingservice$crawlerthread.crawl (inderxingservice.java:71)
At Inderxingservice$crawlerthread.crawl (inderxingservice.java:71)
At Inderxingservice$crawlerthread.crawl (inderxingservice.java:71)
At Inderxingservice$crawlerthread.crawl (inderxingservice.java:71)
At Inderxingservice$crawlerthread.run (inderxingservice.java:49)
The results are also right.
Use poison pills June's attention to things top:
Poison pill objects can only be used if the number of producers and consumers is known. When the producer is more, you can add a counter, when all the producers of meatballs are placed in the queue and then interrupted. Multi-consumer, a producer can put in the same amount of balls as the number of consumers. Because every consumer can only receive a meatball. When both numbers are larger, they are less useful. Only in unbounded queues. Poison pill object can work reliably
Task cancellation for Java concurrent programming (VI)