获取线程对象的名称
String getName():获取线程的名称。
这个方法是放在写在自定义线程类中的,也即是Thread的子类:
public class MyThread extends Thread {
public void run() {
for(int x = 0; x < 100; x++){
System.out.println(getName()+"--"+x);
}
}
}
设置线程对象的名称
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();
}
}
方法2:带参构造方法给线程起名字
public MyThread() {
}
public MyThread(String name){
super(name);
}
MyThread my1 = new MyThread("张三");
MyThread my2 = new MyThread("李四");
获取任意方法所在的线程名称
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();
}
}
}