多线程中this、Thread.currentThread()和this.currentThread()的区别

这篇博客探讨了在Java多线程环境中,`this`、`Thread.currentThread()`和`this.currentThread()`的区别。`this`引用当前对象,而`Thread.currentThread()`返回当前执行的线程实例。在大多数情况下,两者表现一致,除非子类重写了`currentThread()`方法,这时它们的结果可能不同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()返回的结果会不同。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值