Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I have slightly amended your code, not sure if that's what you expect, but at least it terminates! If you use <code>shutdownNow</code> instead of <code>shutdown</code> your workers will be interrupted and unless you put them back to work, will exit with no guarantee that the queue is empty.</p> <pre><code>public class Test { public static void main(String[] args) throws Exception { new Test().run(); } private void run() throws Exception { BlockingQueue&lt;String&gt; processQueue = new ArrayBlockingQueue&lt;&gt;(10000); processQueue.put("lalalalalalalalalalalalala"); //a little longer to make sure there is enough to process ExecutorService service = Executors.newFixedThreadPool(100); for (int i = 0; i &lt; 100; ++i) { service.execute(new Worker(processQueue)); } service.shutdown(); //orderly shutdown = lets the tasks terminate what they are doing service.awaitTermination(1, TimeUnit.SECONDS); //blocks until all tasks have finished or throws TimeOutException if timeout is reached } public static class Worker implements Runnable { private BlockingQueue&lt;String&gt; processQueue = null; private int count = 0; public Worker(BlockingQueue&lt;String&gt; processQueue) { this.processQueue = processQueue; } @Override public void run() { try { do { //tries to get something from the queue for 100ms and returns null if it could not get anything String item = this.processQueue.poll(100, TimeUnit.MILLISECONDS); if (item == null) break; //Ends the job because the queue was empty count++; List&lt;String&gt; resultItems = this.processItem(item); for (String resultItem : resultItems) { this.processQueue.put(resultItem); } } while (true); } catch (InterruptedException e) { System.out.println("Interrupted"); Thread.currentThread().interrupt(); } if (count != 0) System.out.println(Thread.currentThread() + ": processed " + count + " entries"); } private List&lt;String&gt; processItem(String item) { //let's put the string back less final character if (item.isEmpty()) { return Collections.&lt;String&gt; emptyList(); } else { return Arrays.asList(item.substring(0, item.length() - 1)); } } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload