currentThread()函数返回的是“正在调用当前代码段的线程”
this 指代的是本类/实例
用以下代码进行区分:
package thisVScurrentThread;
/**
* PROJECT_NAME: Multi-thread Programming
* PACKAGE_NAME: thisVScurrentThread
*
* @author Jackhow Michael
* @time 01-26 2021 22:54
* @description: 区别this与currentThread()的demo
* currentThread()表示的是当前代码段正在被哪个线程调用
* this 指代本线程类
*/
public class Operate extends Thread{
public Operate() {
System.out.println("--------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("--------end----------");
}
@Override
public void run(){
System.out.println("--------runBegin--------");
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("--------runEnd----------");
}
public static void main(String[] args) {
Operate o = new Operate(); //此时尚未设定实例o的name,默认为thread-0
o.setName("O");
Thread t = new Thread(o);
System.out.println("main begin, t is alive: " + t.isAlive());
t.setName("T");
t.start();
System.out.println("main end, t is alive: " + t.isAlive());
}
}
输出结果如下:
可以直接在Operate类的构造函数中设置Operate类的线程名:this.setName(“O”);
就不会再输出默认值Thread-0