只有线程在创建时命名,才可以用Thread.getName();方法获得名称。。。。

在线程创建时,不用预留String变量存储线程名称。。。。


在创建时命名:MyThread(String name) {

                                    thrd = new Thread(this, name);

                                    thrd.start();

                         }



。。。。不是在创建时,命名的运行结果如下。。


Thread-0是线程的名称,下面是源代码:

package bao;

class MyThread implements Runnable {
    String thrdName;

    MyThread(String name) {
        thrdName = name;
    }

    public void run() {
        System.out.println(thrdName+" startinggg.");
        try {
            for(int count=0; count<10; count++ ) {
                Thread.sleep(400);
                System.out.println("In "+thrdName+", count is "+count);
            }
        }
        catch(InterruptedException exc) {
            System.out.println(thrdName+" interrupted.");
        }
        System.out.println(thrdName+" interrupting.");
    }
}


class D {
    public static void main(String[] args) {
        System.out.println("Main thread starting.");

        MyThread mt = new MyThread("Child #1");

        Thread newThrd = new Thread(mt);

        System.out.println(newThrd.getName());

        newThrd.start();

        System.out.println(newThrd.getName());

        for(int i=0; i<50; i++ ) {
            System.out.print(".");
            try {
                Thread.sleep(100);
            }
            catch(InterruptedException exc) {
                System.out.println("Main thread interrupted.");  
            }
        }

        System.out.println(newThrd.getName());

        System.out.println("Main thread ending.");
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值