Rocky Sinha
Rocky Sinha

Reputation: 93

starting and killing threads at the same time

I have say two threads t1 and t2 which I want to start at the same time (simultaneously), each call System.out.println() to print to console, and then to finish at the same time.

Please advise how to achieve this can it be achieve through executor framework. I am trying to do it with the help of executor framework itself..!!

Upvotes: 0

Views: 104

Answers (1)

assylias
assylias

Reputation: 328785

You can either use 2 CountDownLatches or a CyclicBarrier to do that. For example:

final CountDownLatch start = new CountDownLatch(2);
final CountDownLatch end = new CountDownLatch(2);

Runnable r1 = new Runnable() {
    @Override
    public void run() {
        try {
            start.countDown();
            start.await();
            System.out.println("In 1");
            end.countDown();
            end.await();
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt(); //restore interruption status
        }
    }
};
Runnable r2 = new Runnable() {
    @Override
    public void run() {
        try {
            start.countDown();
            start.await();
            System.out.println("In 2");
            end.countDown();
            end.await();
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt(); //restore interruption status
        }
    }
};

Upvotes: 6

Related Questions