Add Multithreading Function to Java Application using ExecutorService
By admin on Sep 28, 2007 in Java, Programming
In my previous post, I showed you how to do a graceful shutdown of Java application. Now I am going to add multithreading functionalities to the simple example that I developed.
In SampleApp, I declared an instance of ExecutorService, and then I created a default pool size of 10.
private ExecutorService pool;
public SampleApp() {
// Create the thread pool
pool = Executors.newFixedThreadPool(10);
}
In the start method, I submitted the tasks to be executed to the thread pool.
List futureList = new LinkedList();
for (int i = 0; i < 10; i++) {
ProcessorTask task = new ProcessorTask(String.valueOf(i));
Future future = pool.submit(task);
futureList.add(future);
}// You can get the result back from the thread
for (Future future : futureList) {
try {
// Wait with a time out if necessary
//Object obj = future.get(5, TimeUnit.SECONDS);
Object obj = future.get();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
} catch (ExecutionException e) {
System.out.println(e.getMessage());
}
}pool.shutdown();
After submitting the tasks, I can use the Future to return value from the thread.
ProcessorTask is simply a class that extends Runnable which implements the run method.
public class ProcessorTask implements Runnable {
private String name;
public ProcessorTask(String taskName) {
this.name = taskName;
}public void run() {
System.out.println(”Sleeping for 5 seconds for task ” + name);
try {
Thread.sleep(5000);
System.out.println(”Done sleeping for 5 seconds for task ” + name);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
Post a Comment