this指的是当前对象,而Thread.currentThread()指的是当前运行的线程对象,这两者有时不一定相同。
如下列代码所示
public class CountOperate extends Thread{
public CountOperate(){
System.out.println("CountOperate---begin");
System.out.println("current name is "+Thread.currentThread().getName());
System.out.println("Thread.currentThread().isAlive()="+Thread.currentThread().isAlive());
System.out.println("this name is "+this.getName());
System.out.println("this.isAlive()="+this.isAlive());
System.out.println("CountOperate---end");
}
}
main函数
public class Run {
public static void main(String[] args) {
// TODO Auto-generated method stub
CountOperate c = new CountOperate();
Thread t1 = new Thread(c);
}
}
输出结果
Thread.currentThread()和this.currentThread()在大部分情况下结果是相同的,都是调用Thread的静态方法currentThread(),若当前子类重写了父类的currentThread()方法,那么Thread.currentThread()和this.currentThread()返回的结果会不同。
这篇博客探讨了在Java多线程环境中,`this`、`Thread.currentThread()`和`this.currentThread()`的区别。`this`引用当前对象,而`Thread.currentThread()`返回当前执行的线程实例。在大多数情况下,两者表现一致,除非子类重写了`currentThread()`方法,这时它们的结果可能不同。
603

被折叠的 条评论
为什么被折叠?



