Thursday 27 June 2013

Example Thread Runner Using the ExecutorService

Here is a simple example of how to create a thread runner using thread pools. This can be useful during testing or when trying to establish the time it takes for a number of threads to complete.

The Thread

package com.blah.thread.runner;



/**
 * This is a sample class to launch a rule.
 */
public class SomeThread implements Runnable {

String name;
public SomeThread(String name) {
this.name = name;
}

@Override
public void run() {
System.out.println(getName() + " is running");
}
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}


}

The Runner


package com.blah.thread.runner;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class SomeThreadRunner {
private static final int THREAD_POOL_SIZE = 5;
private static final int NO_OF_THREADS = 10;

 public static void main(String[] args) {
long start = System.nanoTime(); 
   ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
   for (int i = 0; i < NO_OF_THREADS ; i++) {
     Runnable worker = new SomeThread("Thread " + i);
     executor.execute(worker);
   }
   //Accept no more threads
   executor.shutdown();
   
   // Wait until all threads are finished
   while (!executor.isTerminated()) {}
   
   long elapsedTime = System.nanoTime() - start;
   System.out.println("Threads took " + elapsedTime / 1000000000.0 + " seconds to complete");
 }

}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.