zoukankan      html  css  js  c++  java
  • 关于Thread.currentThread()和this的差异

    重新来看多线程时,被这结果搞懵逼了。不多说,直接上代码:

    复制代码
     1 public class MyThread02 extends Thread {
     2     public MyThread02() {
     3         System.out.println("init curr: " + Thread.currentThread().getName());
     4         System.out.println("init this: "+this.getName());
     5     }
     6     @Override
     7     public void run() {
     8         System.out.println("run curr: " + Thread.currentThread().getName());
     9         System.out.println("run this: "+this.getName());
    10     }
    11 }
    复制代码
    复制代码
    1 public class Test02 {
    2     public static void main(String[] args) {
    3         MyThread02 target = new MyThread02();
    4         Thread thread = new Thread(target);
    5         thread.setName("A");
    6         thread.start();
    7     }
    8 }
    复制代码
    Result:
    1 init curr: main
    2 init this: Thread-0
    3 run curr: A
    4 run this: Thread-0
    解析:
    row 123的结果很明显,因为Thread.currentThread()是当前代码段正在那个线程调用,MyThread02的构造函数是有main主线程调用的,run是由thread线程调用。同时线程的默认名称是Thread-(No),这点可以有Thread类的构造函数看出。其中一个构造函数如下:
    1 public Thread(Runnable target) {
    2     init(null, target, "Thread-" + nextThreadNum(), 0);
    3 }
    1 /* For autonumbering anonymous threads. */
    2 private static int threadInitNumber;
    3 private static synchronized int nextThreadNum() {
    4     return threadInitNumber++;
    5 }
    重点也就是最后一个this.getName() 为什么是Thread-0?
    由上面的Thread构造函数可以看出当使用一个Runnable对象作为参数去实例化一个Thread对象时,实现Runable的线程类被缓存进了target对象,而当调用run()方法时,Thread类是这样实现的,
    1 public void run() {
    2     if (target != null) {
    3         target.run();
    4     }
    5 }
     由target进行调用,所以this引用的是target,故this.getName() 为target.getName() -->Thread-0;
  • 相关阅读:
    每天玩转3分钟 MyBatis-Plus
    每天玩转3分钟 MyBatis-Plus
    每天玩转3分钟 MyBatis-Plus
    git仓库管理
    【SpringCloud之pigx框架学习之路 】2.部署环境
    【SpringCloud之pigx框架学习之路 】1.基础环境安装
    Ubuntu 14.04 安装mysql
    Netflix是什么,与Spring Cloud有什么关系
    现学现用-我的第三个小小小私活
    申请微信小游戏账号
  • 原文地址:https://www.cnblogs.com/kms1989/p/6015932.html
Copyright © 2011-2022 走看看