您的位置:首页 > 其它

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

2018-01-16 09:37 549 查看
在线程创建时,不用预留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.");

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐