Choose Your Language

Monday 17 March 2014

Run one thread after another in java

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Aravind Sankaran
 */
public class OneThreadRunAfterAnother {
    public static void main(String aravind[]){
        Thread one=new Thread(new Runnable() {

            @Override
            public void run() {             
                for(int x=0;x<=5;x++){
                System.out.println("Aravind");
                }
                System.out.println("");
            }
        });
        one.start();
        Thread two=new SecondThread(one);
        two.start();
    }
}

class SecondThread extends Thread{
    Thread predecessor;
    public SecondThread(Thread predecessor) {
        this.predecessor=predecessor;       
    }
   public void run(){
        if(predecessor!=null&&predecessor.isAlive()){
            try {
                predecessor.join();
                for(int x=0;x<=5;x++){
                System.out.println("Sankaran");
                 }
            } catch (InterruptedException ex) {
             
            }
        }else{
           
        }
    }
}

output:
Aravind
Aravind
Aravind
Aravind
Aravind
Aravind

Sankaran
Sankaran
Sankaran
Sankaran
Sankaran
Sankaran

No comments:

Post a Comment