深入浅出Thread.currentThread()与this的区别

发布时间 2023-12-12 18:04:53作者: x1uc

Thread.currentThread() 与 this 的意义

  1. Thread.currentThread() 可以获取当前线程的引用
  2. this 可以理解为调用当前方法的对象的引用

初步分析

代码如下,生成一个线程,并且启动线程。

public class Main {
    public static void main(String[] args) {
        Point point = new Point();
        point.start();
    }
}

class Point extends Thread {

    @Override
    public void run() {
        System.out.println("------分割线---------");
        Thread thread = Thread.currentThread();
        System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
        System.out.println("this.getName() = " + this.getName());
        System.out.println("Thread.currentThread() == this : " + (Thread.currentThread() == this));
    }
}

image.png
运行结果如图所示,此时我们可以看到,此时this 与 Thread.currentThread()是同一个引用

因为此时Run方法是直接调用的是重写的Run方法,也就是说调用者就是point这个对象本身,所以this = Thread.currentThread。什么时候不直接调用重写的Run方法呢?
可能到这你有点迷惑,但是别着急,接着往下看。

深入分析

我们再看下面这段代码

package org.example;

public class Main {
    public static void main(String[] args) {
        Point point = new Point();
        point.setName("point");
        Thread thread = new Thread(point);
        thread.setName("test");
        thread.start();
    }
}

class Point extends Thread {

    @Override
    public void run() {
        System.out.println("------分割线---------");
        Thread thread = Thread.currentThread();
        System.out.println("Thread.currentThread().getName() =" + Thread.currentThread().getName());
        System.out.println("this.getName() = " + this.getName());
        System.out.println("Thread.currentThread() == this " + (Thread.currentThread() == this));
    }
}

运行结果如下
image.png
我们会发现this 与 Thread.currentThread()不是同一个引用。
image.png
image.png
我们通过对构造方法打断点可以看到,point 被赋值给了 Thread 内的 target 。
那我们在看下Thread内的 Run方法
image.png
我们可以看到最终是由Target对象调用自己的run方法。
所以一切都合理了。

this.getName() 得到的是 调用者也就是Target的name,输出point
currentThread.getName() 得到的是当前线程对象的name,所以输出test(PS:Thread有一个字段存储存储Name)
image.png
image.png