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

1.java多线程中Thread.currentThread() 和 this 的区别:

/**
 * @Description: java多线程中Thread.currentThread() 和 this 的区别
 * @Author: likun
 * @Date: 2021/1/26
 */
public class T {

    public static void main(String[] args) {
        T1 t1 = new T1("T1");
        Thread t2 = new Thread(t1, "T2");

        t1.start();
//        t2.start();
    }
}

class T1 extends Thread {

    private String name;

    public T1(String name) {
        super(name);
        System.out.println("Thread.currentThread()==this :" + (Thread.currentThread() == this));
        System.out.println("Thread.currentThread().isAlive() :" + Thread.currentThread().isAlive());
        System.out.println("Thread.currentThread().getName() :" + Thread.currentThread().getName());
        System.out.println("this.isAlive() :" + this.isAlive());
        System.out.println("this.getName() :" + this.getName());
        System.out.println("=====================================================================");
    }

    @Override
    public void run() {
        System.out.println("Thread.currentThread()==this :" + (Thread.currentThread() == this));
        System.out.println("Thread.currentThread().isAlive() :" + Thread.currentThread().isAlive());
        System.out.println("Thread.currentThread().getName() :" + Thread.currentThread().getName());
        System.out.println("this.isAlive() :" + this.isAlive());
        System.out.println("this.getName() :" + this.getName());

    }
}

2.注释“t1.start();”代码,得到结果:

Thread.currentThread()==this :false
Thread.currentThread().getName() :main
Thread.currentThread().isAlive() :true
this.getName() :T1
this.isAlive() :false
=====================================================================
Thread.currentThread()==this :false
Thread.currentThread().getName() :T2
Thread.currentThread().isAlive() :true
this.getName() :T1
this.isAlive() :false

3.注释“t2.start();”代码,得到结果:

Thread.currentThread()==this :false
Thread.currentThread().getName() :main
Thread.currentThread().isAlive() :true
this.getName() :T1
this.isAlive() :false
=====================================================================
Thread.currentThread()==this :true
Thread.currentThread().getName() :T1
Thread.currentThread().isAlive() :true
this.getName() :T1
this.isAlive() :true

结论:this指Thread中的target,Thread.currentThread()指当前运行的线程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值