Alex Rivera | Logout

Interview: How to ensure that a thread runs after another?

Asked 2012-07-18T15:25:26.843
26

There are thread T1, T2 and T3, how can we ensure that thread T2 run after T1 and thread T3 run after T2?

This question was asked in my interview. I didn't answer. Please explain in detail.

Edit
Report

1 Answer

4

Guess what interviewer asking was three threads do the work in sequence.For example if one thread prints 1,4,5...second 2,5,8 and thirds 3,6,9 etc..ur output should be 1,2,3,4,5..... Ist thread prints 1 and gives chance to 2nd thread to print 2..etc.,

I tried it using cyclebarriers.As soon as 'one' prints 1it gives chance to two as it calls cb.wait,when two runs it will in turn call three in similar fashion and it will continue.Let me know if thr are any bugs in the code

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

class one implements Runnable{
    CyclicBarrier cb;
    one(CyclicBarrier cb){this.cb=cb;}
    public void run(){
        int i=1;
        while(true)
        {
            System.out.println(i);
            try {
                Thread.sleep(1000);
                cb.await();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            i=i+3;
        }
    }

}
class two implements Runnable{
    CyclicBarrier cb;
    int i=2;
    two(CyclicBarrier cb){this.cb=cb;}
    public void run(){


        System.out.println(i);
        try {
            cb.await();
            i=i+3;
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


public class oneTwoThree {
    public static void main(String args[]){
        Runnable threePrinter = new Runnable() {
            int i=3;
            public void run() {
                System.out.println(i);
                i=i+3;
            }
        };


        CyclicBarr
answered 2013-01-22T19:45:58.287

Your Answer