1.3currentThread()方法

currentThread()方法可以返回段正在被哪个线程调用的信息。

示例代码:

public class Main {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName());
    }
}

结果:说明main()被名为main的线程调用。

示例代码:

public class OneThread extends Thread {
    public OneThread() {
        System.out.println("构造方法的打印: " + Thread.currentThread().getName());
    }

    @Override
    public void run() {
        System.out.println("run方法的打印:" + Thread.currentThread().getName());
    }
}

 执行方法:

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

结果:

若执行方法为:

public class Main {
    public static void main(String[] args) {
        OneThread ot = new OneThread();
        ot.run();//注意此处调用的是run(),我们曾提过,调用run()相当于将run()交给其他线程来完成
    }
}

结果:

更复杂的示例:

public class TwoThread extends Thread {
    public TwoThread() {
        System.out.println("Count-Operate--begin");
        System.out.println("Thread.currentThread().getName()= " + Thread.currentThread().getName());
        System.out.println("this.getName()= " + this.getName());
        System.out.println("Count-Operate--end");
    }

    @Override
    public void run() {
        System.out.println("run--begin");
        System.out.println("Thread.currentThread().getName()=" + Thread.currentThread().getName());
        System.out.println("this.getName()= " + this.getName());
        System.out.println("run--end");
    }
}

 执行代码:

public class Main {
    public static void main(String[] args) {
        TwoThread tt = new TwoThread();
        Thread t = new Thread(tt);
        t.setName("A");
        t.start();
    }
}

 结果:

根据结果逆向分析:Thread.currentThread().getName()获得的始终是主线程(也就是说由JVM创建的main线程)。

而由对象本身调用的getName()获取的都是打开的第二个线程Thread-0,也就是执行start()方法的线程。

现在分析发现这个思考是有问题的。

Thread.currentThread().getName()获得的始终是执行start()方法的线程(或者说是调用run()方法的线程)。

而this.getName()获得的都是run()方法所在线程对象的名称。

源码地址:https://github.com/lilinzhiyu/threadLearning

如果有错误欢迎各位指出。

原文地址:https://www.cnblogs.com/lilinzhiyu/p/7930443.html