A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

获取线程对象的名称

String getName():获取线程的名称。
这个方法是放在写在自定义线程类中的,也即是Thread的子类:

public class MyThread extends Thread {

    public void run() {

        for(int x = 0; x < 100; x++){
            System.out.println(getName()+"--"+x);
        }
    }

}
1
2
3
4
5
6
7
8
9
10
设置线程对象的名称

setName(String name)
方法1:无参构造+setXxx()

public class MyThreadDemo1 {

    public static void main(String[] args) {

        // 创建两个线程对象
        MyThread mt1 = new MyThread();
        MyThread mt2 = new MyThread();

        //调用方法设置线程名称
        mt1.setName("张三");
        mt2.setName("李四");

        mt1.start();
        mt2.start();

    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
方法2:带参构造方法给线程起名字

    public MyThread() {
     }

     public MyThread(String name){
         super(name);
     }

         MyThread my1 = new MyThread("张三");
         MyThread my2 = new MyThread("李四");
1
2
3
4
5
6
7
8
9
获取任意方法所在的线程名称

public static Thread currentThread()

public class TwoThreadGetName extends Thread {
   public void run() {
      for (int i = 0; i < 10; i++) {
         printMsg();
      }
   }
   public void printMsg() {
      Thread t = Thread.currentThread();
      String name = t.getName();
      System.out.println("name=" + name);
   }
   public static void main(String[] args) {
      TwoThreadGetName tt = new TwoThreadGetName();
      tt.start();
      for (int i = 0; i < 10; i++) {
         tt.printMsg();
      }
   }
}
---------------------
【转载,仅作分享,侵删】
作者:imxlw00
原文:https://blog.csdn.net/imxlw00/article/details/85331049


1 个回复

倒序浏览
奈斯
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马