zoukankan      html  css  js  c++  java
  • 多线程里面this.getName()和currentThread.getName()有什么区别

    public class hello extends Thread {  
    public hello(){
    System.out.println("Thread.currentThread().getname()="+Thread.currentThread().getName());
    System.out.println("This.getName="+this.getName());
    }
    public void run(){
    System.out.println("Thread.currentThread().getname()="+Thread.currentThread().getName());
    System.out.println("This.getName="+this.getName());
    }
        public static void main(String[] args){
         hello thread =new hello();
         Thread t1 =new Thread(thread);
         t1.setName("A");
         t1.start();
      }
        }

    得到运行结果

    Thread.currentThread().getname()=main
    This.getName=Thread-0
    Thread.currentThread().getname()=A
    This.getName=Thread-0

    为什么呢?

    首先要明白thread和t1是两个完全不同的类,他俩之间唯一的联系就是thread作为一个target传递给了t1,hello thread = new hello();运行这句话的时候会调用hello的构造方法,Thread.currentThread().getName()是获得调用这个方法的线程的名字,在main线程中调用的当然是main了,而this.getName()这个方法是获取当前hello对象的名字,只是单纯的方法的调用。因为没有重写这个方法所以调用的是父类Thread(把这个对象当作是普通的对象)中的方法。

    this.getName()-->public final String getName() {
        return String.valueOf(name);
        }-->所以最终是输出name的值,因为你在hello的构造方法中没有显式调用父类的所以调用的是默认无参的public Thread() {
        init(null, null, "Thread-" + nextThreadNum(), 0);
        }-->最终的名字就是这个"Thread-" + nextThreadNum()-->private static synchronized int nextThreadNum() {
        return threadInitNumber++;
        }-->private static int threadInitNumber;因为是第一次调用nextThreadNum() 方法所以返回值为0-->this.getName()=Thread-0

    后面的输出类似。t1.setName("A");这句话只是修改了t1的名字,和thread对象没有关系,所以run方法中this.getName()的输出还是Thread-0。

  • 相关阅读:
    BZOJ 1726: [Usaco2006 Nov]Roadblocks第二短路
    BZOJ 1708: [Usaco2007 Oct]Money奶牛的硬币
    BZOJ 1642: [Usaco2007 Nov]Milking Time 挤奶时间
    BZOJ 1611: [Usaco2008 Feb]Meteor Shower流星雨
    BZOJ 1610: [Usaco2008 Feb]Line连线游戏
    BZOJ 1609: [Usaco2008 Feb]Eating Together麻烦的聚餐
    BZOJ 1607: [Usaco2008 Dec]Patting Heads 轻拍牛头
    BZOJ 1606: [Usaco2008 Dec]Hay For Sale 购买干草
    BZOJ 1083: [SCOI2005]繁忙的都市
    STL set的用法
  • 原文地址:https://www.cnblogs.com/wxw7blog/p/7300546.html
Copyright © 2011-2022 走看看