ExecutorService with newFixedThreadPool example
The Executor Framework provides different types of executors. Some of them are ..
- SingleThreadExecutor
- FixedThreadPool(n)
- CachedThreadPool
- ScheduledExecutor
Java ExecutorService is an interface in java. It allow in maintaining the thread pool and assign the tasks. Threads execute asynchronously.
package com.threads.example;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
this is just name of the class. we are using the Callable interface for creating the task
*/
public class CallableExample {
public static void main(String[] args) throws InterruptedException, ExecutionException {
/**
Getting the number of cpu core and creating the thread pool according to
cpu count
*/
int c = Runtime.getRuntime().availableProcessors();
ExecutorService service = Executors.newFixedThreadPool(c);
List <Future> listFuture = new ArrayList<Future>();
for(int x =0; x <10; x++) {
Future<Emp> future = service.submit(new Task());
listFuture.add(future);
}
//other operations
Future<Emp> future =null;
for(int x =0; x <10; x++) {
future = listFuture.get(x);
Emp result = future.get();
System.out.println( " future result return : " + result);
}
service.shutdown();
}
}
/**
Callable return the Emp object
*/
class Emp {
String name;
int age;
public static int var;
public Emp() {
super();
}
public Emp(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Emp [name=" + name + ", age=" + age + "]";
}
}
/**
implementing the callable interface
*/
class Task implements Callable<Emp> {
@Override
public Emp call() throws Exception {
Thread.sleep(1000);
return new Emp(Thread.currentThread().getName() , Emp.var++);
}
}
Comments
Post a Comment