类Thread的getName()

tam*_*ria 2 java multithreading

为什么我可以访问该getName()方法?我的类没有扩展类Thread只是实现接口Runnable.

public class MyThread implements Runnable {
    public void run() {
        System.out.println("MyThread is running");
    }

    public static void main(String[] args){
        MyThread thread1 = new MyThread();
        Thread thr = new Thread(thread1, "thread");
        thr.start();
        System.out.println(thr.currentThread().getName());
        System.out.println(thr.getName());//Why do I have access to this method?
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 6

您没有在MyThread类的实例上调用getName(),而是在Thread类的实例上调用它.你应该考虑将你的类重命名为MyRunnable,因为MyThread看起来你的类是某种Thread类,而不是.