53、获取线程对象

获取线程对象

在使用Runnable接口来创建线程的时候,run方法中无法使用Thread类中的getName()方法,这时可以使用Thread.currentThread()方法获取Thread的对象,通过对象调用getName()方法。

package com.sutaoyu.Thread;

public class test_5 {
    public static void main(String[] args) {
        new Thread() {
            public void run() {
                System.out.println(getName() + "hello");
            }
        }.start();
        
        new Thread(new Runnable() {
            public void run(){
                //Thread.currentThread()获取当前正在执行的线程
                System.out.println(Thread.currentThread().getName() + "world");
                
            }
        }).start();
        Thread.currentThread().setName("我是主线程");
        System.out.println(Thread.currentThread().getName());
    }
    
}
原文地址:https://www.cnblogs.com/zhuifeng-mayi/p/10149950.html