关于Thread.currentThread().getName和this.getName()的问题

本文探讨了在Java中如何正确地获取线程名称。通过对比Thread.currentThread().getName()与this.getName()两种方法,详细解释了它们的区别及适用场景。

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

package mythread;
public class CountOperate extends Thread{
    public CountOperate(){
        System.out.println("CountOperate---begin");
        System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName() );
        System.out.println("this.getName() = " + this.getName() );
        System.out.println("CountOperate---end");
    }
    @Override
    public void run(){
        System.out.println("run---begin");
        System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName() );
        System.out.println("this.getName() = " + this.getName() );
        System.out.println("run---end");
    }
}

package test;
import mythread.CountOperate;
public class Run{
    public static void main(String[] args){
        CounOperate c = new CountOperate();
        Thread ti = new Thread(c);
        t1.setName("A");
        t1.start();
    }
}

程序运行结果如下:

CountOperate---begin

Thread.currentThread().getName() = main

This.getName() = Thread-0

CountOperate---end

run---begin

Thread.currentThread().getName = A

this.getName = Thread-0

run---end

造成这样的结果的原因是:currentThread()方法返回的是对当前正在执行的线程对象的引用,this代表的是当前调用它所在函数所属的对象的引用。

使用Thread.currentThread().getName()和使用this.getName(),都可以得到线程的名称,但是使用this调用getName()方法只能在本类中,而不能在其他类中,更不能在Runnable接口中,所以只能使用Thread.currentThread().getName()获取线程的名称,否则会出现编译时异常。

所以以后想过去线程的名称尽量使用Thread.currentThread().getName()。

转载于:https://my.oschina.net/zhanggong/blog/505317

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值