Thread Join



public class ThreadJoin extends Thread{
   
    public void run(){
        for (int i = 0; i < 4; i++) {
         
        try {
            Thread.sleep(1000);
            System.out.println("thread sleep "+i);
            System.out.println(" current thread name "+ Thread.currentThread().getName()); // getting current thread name
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadJoin.class.getName()).log(Level.SEVERE, null, ex); // not for beginners
        }}}   
    public static void main(String[] args) {
       
   
        try {
            ThreadJoin obj = new ThreadJoin();
            ThreadJoin obj1 = new ThreadJoin();
            ThreadJoin obj2 = new ThreadJoin();
            ThreadJoin obj3 = new ThreadJoin();
            System.out.println("thread 1 name "+obj.getName());  // getting and setting of Thread name
            obj.start();
            obj.join(); // used to emphasis that any thread which has to run will run after this thread completion
           
             obj1.start();
              obj1.join(5000);// it is just a priority checker
             obj2.start();
             obj3.start();
// we now set the thread name
            obj.setName("sj");
            System.out.println("after name change " + obj.getName());// here we access the thread name
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadJoin.class.getName()).log(Level.SEVERE, null, ex);
        }
       
       
    }
}

OUTPUT


thread 1 name Thread-0
thread sleep 0
 current thread name Thread-0
thread sleep 1
 current thread name Thread-0
thread sleep 2
 current thread name Thread-0
thread sleep 3
 current thread name Thread-0
thread sleep 0
 current thread name Thread-1
thread sleep 1
 current thread name Thread-1
thread sleep 2
 current thread name Thread-1
thread sleep 3
 current thread name Thread-1
after name change sj
thread sleep 0
thread sleep 0
 current thread name Thread-2
 current thread name Thread-3
thread sleep 1
thread sleep 1
 current thread name Thread-3
 current thread name Thread-2
thread sleep 2
thread sleep 2
 current thread name Thread-2
 current thread name Thread-3
thread sleep 3
thread sleep 3
 current thread name Thread-3
 current thread name Thread-2
BUILD SUCCESSFUL (total time: 12 seconds)





No comments:

Post a Comment