• Thread.currentThread()和this的区别——《Java多线程编程核心技术》


    前言:在阅读《Java多线程编程核心技术》过程中,对书中程序代码Thread.currentThread()与this的区别有点混淆,这里记录下来,加深印象与理解。


    具体代码如下:

     1 public class MyThread09 extends Thread {
     2 
     3     public MyThread09() {
     4         System.out.println("MyThread09 Constructor begin");
     5         System.out.println("Thread.currentThread.getName()=" + Thread.currentThread().getName());
     6         System.out.println("this.getName()=" + this.getName());
     7         System.out.println("MyThread09 Constructor end");
     8     }
     9 
    10     @Override
    11     public void run() {
    12         System.out.println("run begin");
    13         System.out.println("Thread.currentThread.getName()=" + Thread.currentThread().getName());
    14         System.out.println("this.getName()=" + this.getName());
    15         System.out.println("run end");
    16 
    17     }
    18 
    19     public static void main(String[] args) {
    20         MyThread09 thread = new MyThread09();
    21 //        thread.setName("B");
    22         Thread thread1 = new Thread(thread);
    23         thread1.setName("A");
    24         thread1.start();
    25 }

    输出结果如下:

    分析:

    这里将MyThread09的对象作为参数传递给Thread的构造函数,相当于将MyThread09线程委托给thread1去执行,理解这里是非常重要的。

    在MyThread09的构造函数中打印如下内容:

    1 MyThread09 Constructor begin
    2 Thread.currentThread.getName()=main
    3 this.getName()=Thread-0
    4 MyThread09 Constructor end

    第2行:当前线程名为main

    第3行:this.getName()=Thread-0 

    首先看Thread.currentThread方法源码:

    该方法为native的静态方法,返回正在执行该段代码的线程对象。

    这里MyThread09的构造函数是由main线程执行的,所有Thread.currentThread.getName()=main

    再看this.getName()=Thread-0.首先我们看Thread的构造函数源码:

    在初始化线程对象的时候会默认为线程名赋值,格式为“Thread-”的形式。这里的this指的是当前对象,而当前对象就是MyThread09对象,所以打印Thread-0。

    再看其run方法的打印日志:

    1 run begin
    2 Thread.currentThread.getName()=A
    3 this.getName()=Thread-0
    4 run end

    由于我们将MyThread09对象委托给thread1去执行的,所以此时Thread.currentThread.getName()=A,而此时this对象还是表示的MyThread09,所以this.getName()=Thread-0。

    将21行注释打开,运行结果如下:

    1 MyThread09 Constructor begin
    2 Thread.currentThread.getName()=main
    3 this.getName()=Thread-0
    4 MyThread09 Constructor end
    5 run begin
    6 Thread.currentThread.getName()=A
    7 this.getName()=B
    8 run end

    在MyThread09执行构造函数时,还未调用setName方法,所以this.getName()=Thread-0,在执行run方法时,已为其赋值,所以this.getName()=B。

    通过以上分析,可明确清楚Thread.currentThread和this的区别:

    ①Thread.currentThread表示当前代码段正在被哪个线程调用的相关信息。

    ②this表示的是当前对象,与Thread.currentThread有很大的区别。


    by Shawn Chen,2018.12.5日,下午。

  • 相关阅读:
    B
    A
    I
    IIS发布和部署
    编程中什么叫上下文
    浅谈Session,Cookie和http协议中的无状态
    cmd界面输入sqlplus提示不是内外部命令解决方法
    C#已设置安全调试选项,但此选项要求的VS承载进程在此调试中不可用。解决方法
    IIS和IIS Express的区别
    vue.js:634 [Vue warn]: Failed to generate render function: SyntaxError: Unexpected token ')'
  • 原文地址:https://www.cnblogs.com/developer_chan/p/10070067.html
Copyright © 2020-2023  润新知