线程名字的取得和设置

来源:互联网 发布:sz.java.tedu.cn v 编辑:程序博客网 时间:2024/05/22 05:23
public final String getName()

取得线程的方法

public final void setName(String name)

设置线程的方法

由于线程运行的不确定性,因此,取得线程的名字是取得当前线程的名字,取的当前线程的方法是

public static Thread currentThread()

示例代码如下

package com.li;public class ThreadNameTest {    public static void main (String[] args){        ThreadNameTest test = new ThreadNameTest();        ThreadNameTest.MyThread t1 = test.new MyThread();        ThreadNameTest.MyThread t2 = test.new MyThread();        ThreadNameTest.MyThread t3 = test.new MyThread();        //设置线程的名字        t1.setName("线程一");        t2.setName("线程二");        t3.setName("线程三");        //启动线程        t1.start();        t2.start();        t3.start();    }    class MyThread extends Thread{        public void run(){            System.out.println("当前线程的名字为:" + Thread.currentThread().getName());        }    }}

输出的是

当前线程的名字为:线程三当前线程的名字为:线程一当前线程的名字为:线程二

但要注意的是,可能每次输出的顺序不太一样

0 0
原创粉丝点击