Implementation of Join() method of Thread



Implementation of Join()


public class MyReader {

    BufferedReader b;

    public MyReader() {
        b = new BufferedReader(new InputStreamReader(System.in));
    }
    public String readData(String msg){
        String str;
        try{
            System.out.println(msg);
            str=b.readLine();
            return str;
        }catch(Exception e){System.out.println(e);}
        return null;
    }
}

public class NameThread extends Thread{
final MyReader r;
public NameThread(MyReader reader){
    r=reader;
}
    @Override
public void run(){
        synchronized(r){
            String name=r.readData("Enter name");
    System.out.println("Hello,"+name);
        }
  
}
}
public class MailThread extends Thread{
final MyReader r;
public MailThread(MyReader reader){
    r=reader;
}
    @Override
public void run(){
        synchronized(r){
    String mailId=r.readData("Enter mailId");
    System.out.println("your EmailId "+mailId);
        }
  
}

}
public class ReaderTest {

    public static void main(String as[]) throws Exception{
        MyReader m = new MyReader();
        NameThread nt = new NameThread(m);
        MailThread mt = new MailThread(m);
        nt.start(); // NameThread is started(call made for run method of Name thread  by jvm)
        mt.start(); //MailThread is started(call made for run method of Mail thread  by jvm)
        mt.join();//suspend current thread(main thread) till mailThread not complete
        nt.join();//suspend current thread(main thread) till NameThread not complete

        System.out.println("Execution from main start...!");
    }
}


That means join used to start a thread (mt, nt) and again calling join(mt, nt) to stop current thread(main thread) by providing priority to currently started thread.

Comments

Popular posts from this blog

What is Struts Framework?

HOW TO ACCESS SESSION IN STRUTS 2 WITH EXAMPLE

Why java uses both compiler and interpreter?