Thread.currentThread().getName()与this.getName()区别

引用文章已做详细解释请学习

以下本文仅作学习记录:

currentThread是指当前调用代码块的线程(与引用文章中所指的“正在发生这个作用的实体”相对应)

this是指类的实例对象,相关信息都是new产生的对象的信息(可以修改)

package demo01;

public class demo01 {
    public static void main(String[] args) {
        int a = 0;
        /*MyThread myThread = new MyThread(a);
        myThread.setName("C");
        myThread.start();*/
        MyThread myThread = new MyThread(a);
        myThread.setName("H");
        Thread thread = new Thread(myThread);
        thread.setName("A");
        thread.start();
    }
}
class MyThread extends Thread{
    int a;
    public MyThread(int a) {
        this.a = a;

        System.out.println("construct:--begin");
        System.out.println(Thread.currentThread().getName());
        System.out.println(this.getName());
        System.out.println("construct:--end");
    }

    @Override
    public void run() {
        System.out.println("run:--begin");
        System.out.println(Thread.currentThread().getName());
        System.out.println(this.getName());
        System.out.println("run:--end");
        /*while(a<100){
            System.out.println(a++);
        }*/
    }
}

 

你可能感兴趣的:(Java多线程)