Note that there are some explanatory texts on larger screens.

plurals
  1. POExecutors are not running all the threads.
    text
    copied!<p>I'm new to Java, and I'm trying this. I have method, which I wish to run that method in parallel. I wish there should be 10 threads calling the method and get their results. </p> <p>I'm using <code>Callable</code> and <code>Executors</code> for that. I'm creating the thread pool as:</p> <pre><code> ExecutorService executor = Executors.newFixedThreadPool(10); </code></pre> <p>and I when I do this:</p> <pre><code> executor.invokeAll(taskList); </code></pre> <p>out of 10 threads, only 1 thread is been taken from the poll. And I get only this printed:</p> <pre><code>The current thread is pool-1-thread-1 </code></pre> <p>But I wish there should be 10 similar println statements. </p> <p>Here is the full code:</p> <pre><code>import java.util.concurrent.Callable; import java.util.List; import java.util.ArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.Future; import java.util.concurrent.ExecutionException; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutorCompletionService; public class Parallel { public static void main(String args[]) { Learning l = new Learning(); l.message = "1st Object"; l.testThread(); } } //this class deals with threads class Learning { public String message; public void setMessage(String message) { this.message = message; } //contains the code where public void testThread() { //create a callable for each method Callable&lt;String&gt; callable1 = new Callable&lt;String&gt;() { @Override public String call() throws Exception { System.out.println("The current thread is " + Thread.currentThread().getName()); return method1(); // return null; } }; //add to a list List&lt;Callable&lt;String&gt;&gt; taskList = new ArrayList&lt;Callable&lt;String&gt;&gt;(); taskList.add(callable1); //create a pool executor with 10 threads ExecutorService executor = Executors.newFixedThreadPool(10); try { List&lt;Future&lt;String&gt;&gt; futureList = executor.invokeAll(taskList); } catch (InterruptedException ie) { } } //put your code here! private String method1() { return Thread.currentThread().getName(); } } </code></pre> <p>Am I missing something here? </p>
 

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