Java多线程之this与Thread.currentThread()的区别

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("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 ");
        System.out.println("Thread.currentThread()==this :"+ (Thread.currentThread() == this));
    }

    @Override
    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("Thread.currentThread()==this :"+ (Thread.currentThread() == this));
        System.out.println("this.getName()=" + this.getName());
        System.out.println("this.isAlive()=" + this.isAlive());
        System.out.println("run --- end");
    }
}
public class Run {

    public static void main(String[] args){

        CountOperate c = new CountOperate();
        Thread t1 = new Thread(c);
        System.out.println("main begin t1 isAlive=" + t1.isAlive());
        t1.setName("A");
        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.isAlive()=false
CountOperate---end 
Thread.currentThread()==this :false
main begin t1 isAlive=false
main end t1 isAlive=true
run---begin
Thread.currentThread().getName=A
Thread.currentThread().isAlive()true
Thread.currentThread()==this :false
this.getName()=Thread-0
this.isAlive()=false
run --- end

CountOperat()部分
由于构造函数是被main主线程调用的,所以这里的Thread.currentThread()返回的是主线程main。
其实就是表明Thread.currentThread()表示当前代码段正在被谁调用。
而this就是只当前线程myThread。至于this.getName()=Thread-0是有其内部机制决定的。

run()方法部分:
Thread.currentThread()与this指向了不通的线程对象。Thread.currentThread()指向的是外部线程,表示当前方法被外部线程t1调用。this指向的是内部线程myThread,状态依旧是false未开启状态。与main方法中的输出一样。

结论
在线程不作为参数传入另一个线程时,this和Thread.currentThread()代表的是同一个对象。而当线程作为参数传入时,this指向当前对象,即内部线程,而Thread.currentThread()指向当前方法被哪个线程调用的那个对象,即外部线程。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值