【问题标题】:how to execute join(); function on mainThread?如何执行join(); mainThread 上的函数?
【发布时间】:2020-03-27 17:12:48
【问题描述】:

我正在尝试执行 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 multithreading nullpointerexception


【解决方案1】:

更正的代码。你没有加入子类usign join。相反,你在main中加入方法到你的线程会将线程加入到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 ");
        }

    }
}

【讨论】:

  • 我想让子线程等到主线程执行而不是相反
  • @Esraa Salama :线程通常具有协调器和工作器概念,其中工作器处理子线程和主线程,即协调器等待子线程完成其处理/任务。它通常是这样的。无法想出你的代码会有帮助的场景。同样使用带线程的静态是有风险的,不是一个好的做法。
【解决方案2】:

那是因为你没有。

在你的主线程中,你运行t1.mainthread =,引用静态字段t1。然后你创建另一个MyThread实例,这意味着它有自己的主线程变量版本,你还没有设置那个.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-22
    • 2018-06-24
    • 2020-05-19
    • 2018-06-24
    • 2012-03-30
    • 1970-01-01
    • 2021-02-23
    相关资源
    最近更新 更多