如何执行join();mainThread 上的函数?

how to execute join(); function on mainThread?

提问人: 提问时间:12/3/2019 更新时间:12/3/2019 访问量:246

问:

我正在尝试执行join();主线程上的函数 为了获取主线程对象,我使用了来自 Thread.currentThread() 的引用;通过以下代码,但它经常给我一个 NullPointerException,就好像主线程尚未初始化一样:

    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");

    }

    }

子线程类:

     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();
    }

}

它经常给我一个 NullPointerException,就好像主线程尚未初始化一样

Java 多线程 NullPointerException

评论

0赞 ThuongLe 12/3/2019
看看这个 stackoverflow.com/questions/18479771/...

答:

0赞 tarun 12/3/2019 #1

更正了代码。您不加入子类 usign join。取而代之的是,在 main 中,您将 join 方法连接到您的线程,将线程连接到 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 ");
        }

    }
}

评论

0赞 12/3/2019
我想让子线程等到主线程执行,而不是相反
0赞 tarun 12/3/2019
@Esraa Salama :线程通常具有协调器和工作器的概念,其中工作器进行处理,又名子线程,主线程又名协调器等待子线程完成其处理/任务。一般都是这样。无法提出您的代码会有所帮助的场景。此外,将静态与线程一起使用是有风险的事情,不是一个好的做法。
1赞 rzwitserloot 12/3/2019 #2

那是因为你没有。

在你的main中,你运行,指的是静态字段。然后,稍后创建另一个 MyThread 实例,这意味着它有自己的 mainthread 变量版本,并且您尚未设置该版本。t1.mainthread =t1