获取当前线程名称
方式一:
this.getName()获取线程名称,该方法适用于继承Thread实现多线程方式。
class GetName1 extends Thread {
@Override
public void run(){
System.out.println(this.getName());
}
}
方式二:
Thread.currentThread.getName()获取线程名称,该方法适用于实现Runnable接口实现多线程方式。
class GetName2 implements Runnable {
@Override
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
设置线程名称
方式一:
通过构造方法设置线程名称。
class SetName1 extends Thread {
public SetName1(String name){
super(name);
}
@Override
public void run(){
System.out.println(this.getName());
}
}
public class SetNameThread {
public static void main(String[] args){
SetName1 setName1 = new SetName1("SetName1");
setName1.start();
}
}
方式二:
通过setName()方法设置线程名称。
class SetName2 implements Runnable {
@Override
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
public class SetNameThread {
public static void main(String[] args){
Thread thread = new Thread(new SetName2());
thread.setName("SetName2");
thread.start();
}
}