JAVA中的Thread.currentThread是什么意思

当年学的时候,我也纳闷,为什么获取当前线程需要调用Thread类的静态方法去获取,为毛不直接用对象操作就行了啊?
上代码先:

class MyThread extends Thread {

@Override
public void run() {
try {
Thread.sleep(500);
Thread t = Thread.currentThread();
System.out.println("当前线程名字:" + t.getName() + " 当前线程的优先级别为:"+ t.getPriority() + " ID:" + t.getId());
// System.out.println("当前线程名字:" + this.getName() + " 当前线程的优先级别为:" + this.getPriority() + " ID:"+ this.getId());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class TestDemo {
public static void main(String[] args) {
MyThread mt = new MyThread();
new Thread(mt, "Name1").start();
new Thread(mt, "Name2").start();
new Thread(mt).start();
System.out.println(Thread.currentThread().getName()); // main主方法
}
}

看上面,貌似你会用Thread.currentThread()。
但是问题来了,为毛不直接用对象操作就行了啊?
把run()方法里的Thread.currentThread() 直接替换成 this不就行了(替换成注释掉的代码),直接用对象多省事啊。
不知你们学习时有没有过这样的疑惑,因为我确实想不到哪里需要调用到这个线程而拿不到这个线程的情况。

可是新的问题又出现了,你试试看运行上面这段代码,this和Thread.currentThread()输出的内容是否相同?

行比较一下吧。没想到吧,差别明显啊!所以题外插一句:如果调用isInterrupted返回true,this就是当前线程对象,此时
Thread.currentThread()与this表示同一对象。否则,就必须使用Thread.currentThread()获取当前线程。

而且既然是使用到了多线程,多半情况下都不会知道系统当前执行的是哪块线程,所以你需要调用Thread.currentThread()方法来获取系统当前正在执行的一条线程,然后才可以对这个线程进行其他操作,就是这个意思。

https://zhidao.baidu.com/question/691200709162399644.html

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值