ExecutorService

Here is refresher of multithreading in java.

Java (since 1.5) has come up with more controlled and cleaner way to handle threads, i.e. ExecutorService.

ExecutorService is a way in which we can create thread pools and execute threads in controlled manner, i.e. can define number of threads to be allowed at the same time.

ExecutorService ex = Executors.newSingleThreadExecutor();
ExecutorService ex = Executors.newFixedThreadPool(5);
ExecutorService ex = Executors.newScheduledThreadPool(10);

In first case we are creating a singlethreaded pool, whereas in second case we are defining a pool of fixed length. In third case we are creating a pool of threads which can perform activities at a defined time.

Read more
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html
http://tutorials.jenkov.com/java-util-concurrent/executorservice.html

A simple code example

public class test {
public static void main(String s[])
{
ExecutorService executor = Executors.newFixedThreadPool(5);
for(int i=0;i<10;i++) { executor.execute(new RunTest()); executor.execute(new RunTest2()); } executor.shutdown(); } } class RunTest implements Runnable { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO Auto-generated method stub System.out.println("run"+Thread.currentThread().getName()); } } class RunTest2 implements Runnable { @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO Auto-generated method stub System.out.println("run2"+Thread.currentThread().getName()); } }

Play around with thread pool size to understand the usage.