Monday, October 3, 2011

How to Start Threads at the Same Time in Java

Suppose we need to start few threads in Java at the same time, the easy way to do it by using something like below.
public class WithForLoop {

    private static final int NUM_THREADS = 5;

    public static void main(String[] args) {
        for (int i = 0; i < NUM_THREADS; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(String.format(
                        "%s: Do something....",
                        Thread.currentThread().getName()));
                }
            }).start();
        }
    }
}
The problem with it is that we give a head-start for thread 1 to start first. For most cases, it may not matter, but if let's say we need to make sure all the threads get started at the same time, we can make use of java.util.concurrent.CountDownLatch.

import java.util.concurrent.CountDownLatch;

public class WithCountDownLatch {

    private static final int NUM_THREADS = 5;

    public static void main(String[] args) {
        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(NUM_THREADS);
        for (int i = 0; i < NUM_THREADS; i++) {
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        try {
                            startGate.await();
                            System.out.println(String.format(
                                 "%s: Do something....",
                                 Thread.currentThread().getName()));
                        } finally {
                            endGate.countDown();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
        }
        
        // this will cause all the threads to get executed concurrently
        startGate.countDown();
        try {
            endGate.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

No comments:

Post a Comment