You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在另一个类的子线程中获取主线程引用?

解决方案:在子线程类中获取主线程引用

你的问题核心是跨类访问静态成员的语法错误,以及线程实例创建的笔误,下面分两种方式解决:

方式一:直接访问目标类的静态变量

mainthread是JoinMethod2类的静态成员,Test5类和它没有继承关系,不能用super访问,必须通过类名直接引用。同时要确保静态变量的访问权限允许:

  1. 调整JoinMethod2的静态变量权限(如果Test5和它不在同一个包,需要改为public):
public class JoinMethod2 extends Thread{
    // 改为public确保跨包可访问;同包下可保留默认权限
    public static Thread mainthread;
    public static void main(String[] args) throws InterruptedException {
        mainthread=Thread.currentThread();
        
        // 修正笔误:启动Test5实例而非JoinMethod
        Test5 th = new Test5();
        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);
        }
    }
}
  1. 在Test5的run方法中通过类名访问静态变量:
class Test5 extends Thread {
    public void run (){
        try {
            // 直接通过类名引用静态变量
            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);
        }
    }
}

方式二:通过构造方法传递主线程引用(推荐)

依赖静态变量会增加类之间的耦合度,更优雅的方式是在创建子线程实例时,把主线程引用通过构造方法传递进去:

  1. 修改Test5类,添加构造方法接收Thread参数:
class Test5 extends Thread {
    private Thread mainThread;
    
    // 构造方法接收主线程引用
    public Test5(Thread mainThread) {
        this.mainThread = mainThread;
    }
    
    public void run (){
        try {
            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);
        }
    }
}
  1. 在JoinMethod2的main方法中传递主线程引用:
public class JoinMethod2 extends Thread{
    public static void main(String[] args) throws InterruptedException {
        Thread mainthread=Thread.currentThread();
        
        // 创建Test5实例时传入主线程引用
        Test5 th = new Test5(mainthread);
        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);
        }
    }
}

关键说明

  • 你原来的代码中启动的是JoinMethod实例,这是笔误,必须替换为Test5,否则子线程不会执行Test5的run方法。
  • 方式二更符合面向对象设计原则,避免了静态变量带来的全局依赖,代码的可维护性和灵活性更强。

内容的提问来源于stack exchange,提问作者Fahyien sher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 22:24:27