Home > Net >  How to get the main thread reference in a child thread which is in another class?
How to get the main thread reference in a child thread which is in another class?

Time:08-26

public class JoinMethod2 extends Thread{
    static Thread mainthread;
    public static void main(String[] args) throws InterruptedException {
        mainthread=Thread.currentThread();
        
        JoinMethod th = new JoinMethod();
        th.start();
        try {
            
            for(int i = 1; i<=5; i  ) {
                System.out.println("Main Thread " i);
                Thread.sleep(1000);
                }
            }
            catch(Exception e) {
                System.out.println(e);
            }
            }
}
    
class Test5 extends Thread {
public void run (){
        super.mainthread;//THIS IS NOT WORKING
        try {
            mainthread.join();//THIS IS NOT WORKING
        for(int i = 1; i<=5; i  ) {
            System.out.println("Child Thread " i);
            Thread.sleep(1000);
            }
        }
        catch(Exception e) {
            System.out.println(e);
        }
        }
    }

How to get the main thread reference in a child thread which is in another class?

CodePudding user response:

Make the mainthread static field public so it can be accessed from outside of JoinMethod2.

public class JoinMethod2 extends Thread {

    // Note: mainthread is now "public"
    public static Thread mainthread;

    public static void main(String[] args) throws InterruptedException {
        mainthread = Thread.currentThread();

        JoinMethod th = new JoinMethod();
        th.start();

        try {
            for (int i = 1; i <= 5; i  ) {
                System.out.println("Main Thread "   i);
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

class Test5 extends Thread {
    public void run () {
        try {

            // Note: Access the now "public" mainthread field
            JoinMethod2.mainthread.join();

            for (int i = 1; i <= 5; i  ) {
                System.out.println("Child Thread " i);
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

CodePudding user response:

For calling the parent class static reference in child class we have to mention the reference along with parent class name(eg.JoinMethod.mainthread.join();). For calling the static methods, variables in another class, always write Parent class name(.) along with methods or variables.

  • Related