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()指当前运行的线程。