Loading

currentThread()方法返回代码段正在被哪个线程调用

currentThread()方法返回代码段正在被哪个线程调用

package com.stono.thread2.page16;

public class MyThread extends Thread{
    public MyThread() {
        System.out.println("构造方法的打印:"+Thread.currentThread().getName());
    }
    @Override
    public void run() {
        System.out.println("run方法的打印:"+Thread.currentThread().getName());
    }
    
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
//        myThread.start();
//        构造方法的打印:main
//        run方法的打印:Thread-0

        myThread.run();
//        构造方法的打印:main
//        run方法的打印:main

    }
}

 注意与this.getName()的区别

package com.stono.thread2.page16;

public class CountOperate extends Thread{
    public CountOperate() {
        System.out.println("CountOperate---begin");
        System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName());
        System.out.println("this.getName()="+this.getName());
        System.out.println("CountOperate---end");
    }
    @Override
    public void run() {
        // super.run();
        System.out.println("run---begin");
        System.out.println("Thread.currentThread().getName()="+Thread.currentThread().getName());
        System.out.println("this.getName()="+this.getName());
        System.out.println("run---end");
        
    }
    
    public static void main(String[] args) {
        CountOperate c = new CountOperate();
        Thread t1 = new Thread(c);
        t1.setName("A");
        t1.start();
//    CountOperate---begin
//    Thread.currentThread().getName()=main
//    this.getName()=Thread-0
//    CountOperate---end
//    run---begin
//    Thread.currentThread().getName()=A
//    this.getName()=Thread-0
//    run---end
    }

}

 this.getName()是Thread.getName()方法,源码:

    public final String getName() {
        return new String(name, true);
    }

 

posted @ 2018-01-28 10:57  stono  阅读(904)  评论(0编辑  收藏  举报