-1

I am trying to execute join(); function on main thread TO get a main thread object I have used a reference from Thread.currentThread(); by the following code but it often gives me a NullPointerException as if mainthread has not been intialized:

    public class Main{

     MyThread t1 = new MyThread();

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

    MyThread t = new MyThread();
    t.start();

    for (int i = 0; i<10 ; i++) 
        System.out.println("main thread");

    }

    }

The child thread classs :

     public class MyThread extends Thread {

     Thread mainthread ;    

@Override
public void run() {

    for (int i = 0; i<10 ; i++) 
        System.out.println("child thread ");
    try {
        mainthread.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

It often gives me a NullPointerException as if mainthread has not been intialized

  • Have a look up this https://stackoverflow.com/questions/18479771/java-multithreading-concept-and-join-method – ThuongLe Dec 03 '19 at 04:01

2 Answers2

1

That's because you haven't.

In your main, you run t1.mainthread =, referring to static field t1.Then later you create another instance of MyThread, which means it has its own version of the mainthread variable, and you haven't set that one.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
0

Corrected code.You do not join in the childclass usign join.Instead in main you join method to your thread will join the the thread to main

public class Main {
    MyThread t1 = new MyThread();

    public static void main(String[] args) throws InterruptedException {

        MyThread t = new MyThread();
        t.start();

        for (int i = 0; i < 10; i++)
            System.out.println("main thread");

        // This will join your thread with main thread
        t.join();

    }
}

class MyThread extends Thread {

    Thread mainthread;

    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {
            System.out.println("child thread ");
        }

    }
}
tarun
  • 218
  • 2
  • 11
  • I want to make child thread wait until execution of main thread not the opposite –  Dec 03 '19 at 04:17
  • @Esraa Salama : Threads ussually have coordinator and worker concept where worker does processing aka child thread andmain thread aka coordinator waits for child thread to complete its processing/task. Its generally like that.Cannot come up with a scenario where yur code will be helpful. Also using static with threads is risky affair and not a good practice. – tarun Dec 03 '19 at 04:31