java如何设置线程的名字?

2025-11-04 00:05:05

1、首先写一个类继承Thread ,重写run方法,利用GetName();

2、public class SetnameDemo extends Thread {

@Override

public void run() {

//getName

// public final String getName()返回该线程的名称。 

//

// 返回:

// 该线程的名称。

for (int i = 0; i < 100; i++){

System.out.println(getName() + i);

}

}

}

3、写好测试类:

public class SetnameMain {

public static void main(String[] args) {

SetnameDemo sd = new SetnameDemo();

SetnameDemo sd1 = new SetnameDemo();

sd.setName("haha:");

sd1.setName("heheh:");

sd.start();

sd1.start();

//获取主线程的名字:

//因为currentThread返回的是Thread,而Thread有getName的方法!

System.out.println("--------------"+Thread.currentThread().getName());

}

}

4、为什么主线程获取线程名字要用 Thread.currentThread().getName()呢?

这是因为,主线程没有继承Thread类,当然不能用里面的方法,但是,Thread.curretnThread()是返回Thread这个对象的,所以这样就可以getName了!!

5、所以控制台运行的结果如下:

--------------main

hehehe:0

hahha:0

hehehe:1

hahha:1

hahha:2

hehehe:2

hehehe:3

hahha:3

hehehe:4

hahha:4

hehehe:5

hehehe:6

hehehe:7

hehehe:8

hehehe:9

hehehe:10

hahha:5

hehehe:11

hehehe:12

hehehe:13

hehehe:14

hehehe:15

hehehe:16

hahha:6

hehehe:17

hahha:7

hehehe:18

hahha:8

.

.

.

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢