Java线程中currentThread和this的区别

总结:

this指正在被调用的线程对象

currentThread是返回该代码段被哪个线程调用

看个例子:

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

测试代码:

public static void main(String[] args) {
        CountOperate c= new CountOperate();
        c.setName("CountOperate");
        c.start();
        Thread t1 = new Thread(c);
        System.out.println("main begin t1 isAlive="+t1.isAlive());
        t1.setName("t1");
        t1.start();
        System.out.println("main end t1 isAlive="+t1.isAlive());

得出结果

CountOperate—begin
Thread.currentThread().getName()=main
Thread.currentThread().isAlive()true
this.getName()Thread-0           这里这个this是CountOperate类的对象,CountOperate继承了Thread
this.isAlive()false

CountOperate—end

main begin t1 isAlive=false
main end t1 isAlive=true

run—begin
Thread.currentThread().getName()=CountOperate
Thread.currentThread().isAlive()true
this.getName()CountOperate
this.isAlive()true

run—end

run—begin
Thread.currentThread().getName()=t1
Thread.currentThread().isAlive()true
this.getName()CountOperate
this.isAlive()false

run—end


参考高洪岩的《Java多线程编程核心技术》

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值