获取线程对象

在使用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());
    }
    
}

 

相关文章:

  • 2021-12-11
  • 2021-08-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-21
相关资源
相似解决方案