一、获取线程的名称
在java中,获取线程的名称可以通过getName()方法,这个方法返回一个String类型。
public static void main(String[] args) {
// 获取正在执行任务的线程
Thread thread = Thread.currentThread();
// 获取线程的名称
String threadName = thread.getName();
System.out.println(threadName);
}
二、设置线程的名称
在java中,设置线程的名称可以通过setName()方法,这个方法只有一个参数name,它用来指定新的线程的名称,这个方法没有返回值,同时,它还是一个同步方法,这也就意味着,多个线程同时执行该方法时,也不会出现线程安全问题。
public static void main(String[] args) {
// 获取正在执行任务的线程
Thread thread = Thread.currentThread();
// 获取线程的名称
String threadName = thread.getName();
System.out.println("当前线程的名称" + threadName);
// 设置线程的名称
thread.setName("main02");
// 获取线程的名称
threadName = thread.getName();
System.out.println("当前线程的新名称" + threadName);
}
}