Java教程

Java setName()方法

线程类的 setName()方法用于更改线程的名称。

语法

public final void setName(String a)

参数

a = It shows the new name for the thread.

返回

this method does not return any value.

异常

SecurityException: 如果当前线程无法修改该线程,则会引发此异常。

例子

public class SetNameExample extends Thread
{
    public void run()
    {
        System.out.println("running...");
    }
    public static void main(String args[])
    {
        // creating two threads
        SetNameExample t1=new SetNameExample();
        SetNameExample t2=new SetNameExample();
        // start of thread
        t1.start();
        t2.start();
        // change the thread name
        t1.setName("Sonoo Jaiswal");
        t2.setName("lidihuo");
        // print the thread after changing
        System.out.println("After changing name of t1: "+t1.getName());
        System.out.println("After changing name of t2: "+t2.getName());
    }
}
输出:
After changing name of t1: Sonoo Jaiswal
running...
running...
After changing name of t2: lidihuo

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4