1.

How To Construct A Thread Pool With 2 Threads That Executes Some Tasks That Return A Value?

Answer»

You can create a fixed thread pool USING the newFixedThreadPool() method of the Executors class.

// creating EXECUTOR with pool of 2 threads
ExecutorService ex = Executors.newFixedThreadPool(2);
// running tasks
Future f1 = ex.submit(new Task());
Future f2 = ex.submit(new Task());
try {
// getting the future VALUE
System.out.println("Future f1 " + f1.get());
System.out.println("Future f1 " + f1.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ex.shutdown();

You can create a fixed thread pool using the newFixedThreadPool() method of the Executors class.

// creating executor with pool of 2 threads
ExecutorService ex = Executors.newFixedThreadPool(2);
// running tasks
Future f1 = ex.submit(new Task());
Future f2 = ex.submit(new Task());
try {
// getting the future value
System.out.println("Future f1 " + f1.get());
System.out.println("Future f1 " + f1.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ex.shutdown();



Discussion

No Comment Found