命名线程和当前线程

Thread类提供了更改和获取线程名称的方法。默认情况下,每个线程都有一个名称,即thread-0thread-1, ...等。 可以使用setName()方法更改线程的名称。 setName()getName()方法的语法如下:

  • public String getName() : 用于返回线程的名称。
  • public void setName(String name): 用于更改线程的名称。

命名线程的示例

package com.zyiz;

class TestMultiNaming1 extends Thread {
    public void run() {
        System.out.println("running...");
    }

    public static void main(String args[]) {
        TestMultiNaming1 t1 = new TestMultiNaming1();
        TestMultiNaming1 t2 = new TestMultiNaming1();
        System.out.println("Name of t1:" + t1.getName());
        System.out.println("Name of t2:" + t2.getName());

        t1.start();
        t2.start();

        t1.setName("New ThreadName");
        System.out.println("After changing name of t1:" + t1.getName());
    }
}

执行上面示例代码,得到以下结果:

Name of t1:Thread-0
Name of t2:Thread-1
After changing name of t1:New ThreadName
running...
running...

当前线程

currentThread()方法返回当前正在执行的线程的引用。函数的原型如下:

public static Thread currentThread()

currentThread()方法的示例

package com.zyiz;

class TestMultiNaming2 extends Thread {
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }

    public static void main(String args[]) {
        TestMultiNaming2 t1 = new TestMultiNaming2();
        TestMultiNaming2 t2 = new TestMultiNaming2();

        t1.start();
        t2.start();
    }
}

执行上面示例代码,得到以下结果:

Thread-1
Thread-0

上一篇:加入线程

下一篇:线程优先级

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程