新线程: Thread-0,Thread-1,Thread-2 */publicclassDemo01GetThreadName{publicstaticvoidmain(String[] args){//创建Thread类的子类对象MyThreadmt=newMyThread();//调用start方法,开启新线程,执行run方法mt.start();newMyThread().start();newMyThread().start();//链式编程System.out.println(Thread.curren...
② run方法: Thread.currentThread.getName(): run方法是由我们new 出来的MyThread() 调用start方法执行的.所以 Thread.currentThread.getName(): 的结果是Thread-0 this.getName(): 这个方法中的this,代表本类对象,在代码中是MyThread 所以这个方法获得的名字是Thread-0 可能会有疑惑,为什么都是Thread-0 而不...
在Java中,getName方法通常用于获取线程的名称。如果线程不存在或者出现异常,getName方法可能会抛出SecurityException或者NullPointerException异常。 为了处理这些异常,可以使用try-catch语句来捕获并处理异常。例如: Thread thread = new Thread(); try { String threadName = thread.getName(); System.out.println("Thre...
println("当前线程的名称为:" + threadName); 复制代码 设置线程的名称:可以通过Thread类的setName方法设置线程的名称,例如: Thread currentThread = Thread.currentThread(); currentThread.setName("MyThread"); System.out.println("当前线程的名称为:" + currentThread.getName()); 复制代码 获取类的名称:通过...
System.out.println("当前执行的线程的名称是:"+threadName); 1. 这行代码将在控制台输出当前执行的线程的名称。 示例代码 下面是整个过程的示例代码: publicclassGetCurrentThreadName{publicstaticvoidmain(String[]args){// 步骤一:获取当前执行的线程对象ThreadcurrentThread=Thread.currentThread();// 步骤二:从...
public class ThreadDemo { public static void main(String[] args) { Thread t1 = new MyThread(); // 获取子线程默认名称 System.out.println(t1.getName()); // Thread-0 // 设置线程名称 t1.setName("1号线程"); t1.start(); Thread t2 = new MyThread(); ...
getName()方法用于获取线程的名称,返回一个字符串。我们将获取到的线程名称存储在threadName变量中,并将其打印出来。 当我们运行上述代码时,将看到如下输出: Thread name: MyThread 1. 总结 通过上述步骤,我们可以很容易地实现在 Java 中获取线程名称的功能。首先,我们创建一个线程实例;然后,为线程设置一个名称;最...
Java 实例 - 获取当前线程名称 Java 实例 以下实例演示了如何通过继承 Thread 类并使用 getName() 方法来获取当前线程名称: TwoThreadGetName.java 文件 [mycode3 type='java'] public class TwoThreadGetName extends Thread { public void run() { for .
public class ThreadTest{ public static void main(String args[]){ //获取主线程的名字 //先通过Thread.currentThread()方法返回当前线程,然后调用该线程里的getName()方法,获取当前线程的名字 System.out.println("当前线程名字为:" + Thread.currentThread().getName()); ...
In this article, we will learn toset and get thread names in Javawith simple examples using the built-in methodssetName()andgetName()in theThreadclass. 1. Getting Thread Name By default, the Java compiler sets a default name of each threadwhile creating, and we can get the thread name...