Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <code>taskList</code> has only one <code>callable</code> in it. Add more <code>callable</code>s to the list and sleep for sometime in <code>method1()</code> so that all 10 threads in the pool get busy.</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[10]; for(int i=0;i&lt;10;++i){ callable1[i] = 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;(); for(int i=0;i&lt;10;++i){ taskList.add(callable1[i]); } //create a pool executor with 10 threads ExecutorService executor = Executors.newFixedThreadPool(10); try { List&lt;Future&lt;String&gt;&gt; futureList = executor.invokeAll(taskList); executor.shutdown(); } catch (InterruptedException ie) { } } //put your code here! private String method1() { return Thread.currentThread().getName(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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