Java获取、修改线程对象的名字

获取当前线程对象static Thread currentThread()

Thread t = Thread.currentThread();//返回值t就是当前线程
public class ThreadTest04 {
    
    
    public static void main(String[] args) {
    
    
        //创建线程对象
        MyThead2 t = new MyThead2();
        //设置线程的名字
        t.setName("t1");
        //获取线程的名字
        t.getName();
        //启动线程
        t.start();
        String tName = t.getName();
        System.out.println(tName);


        MyThead2 t2 = new MyThead2();
        t2.setName("t2");
        String t2Name = t2.getName();
        System.out.println(t2Name);

        t2.start();
    }
}

class  MyThead2 extends Thread{
    
    
    @Override
    public void run() {
    
    
        for (int i = 0; i < 100; i++) {
    
    
        	//currentThread就是当前线程对象。
        	//当t1线程执行run方法,那么这当前线程就是t1;
        	//当t2线程执行run方法,那么这当前线程就是t2;
            Thread currentThread = Thread.currentThread();
            System.out.println( currentThread.getName() + "-->" + i);
        }
    }
}

运行截图:
在这里插入图片描述

获取线程对象的名字String name = 线程对象.getName();

修改线程对象的名字线程对象.setName("线程名字");

当线程没有设置名字的时候,默认的名字有什么规律
Thread-0;
Thread-1;
Thread-2…

public class ThreadTest04 {
    
    
    public static void main(String[] args) {
    
    
        //创建线程对象
        MyThead2 t = new MyThead2();
        //设置线程的名字
        t.setName("tttt");
        //获取线程的名字
        t.getName();
        //启动线程
        t.start();

        String tName = t.getName();
        System.out.println(tName);//如果不设置线程的名字就是:Thread-0

        MyThead2 t2 = new MyThead2();
        System.out.println(t2.getName());//Thread-1
    }
}

class  MyThead2 extends Thread{
    
    
    @Override
    public void run() {
    
    
        for (int i = 0; i < 100; i++) {
    
    
            System.out.println("分支线程-->" + i);
        }
    }
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq2632246528/article/details/114799823