为什么我可以访问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?
}
}
答案 0 :(得分:6)
您没有在MyThread类的实例上调用getName(),而是在Thread类的实例上调用它。你应该考虑将你的类重命名为MyRunnable,因为MyThread看起来你的类是某种Thread类,而不是。
答案 1 :(得分:0)
您执行的每个操作都在一个帖子中。如果你正在做一些动作,在启动程序的main方法中,它发生在主线程中。
方法currentThread是静态的,它提供当前正在执行该行的线程,当你执行时,getName()就在那个Thread对象上。