Thread类中的静态方法

时间:2022-09-17 19:09:37

1、currentThread()

currentThread()方法返回的是对当前正在执行线程对象的引用

package thread;
/**
 * 线程类的构造方法、静态块是被main线程调用的,而线程类的run()方法才是应用线程自己调用的
 * 
 */
public class MyThread04 extends Thread
{
    static
    {
        System.out.println("静态块的打印:" + 
                Thread.currentThread().getName());    
    }
    
    public MyThread04()
    {
        System.out.println("构造方法的打印:" + 
                Thread.currentThread().getName());    
    }
    
    public void run()
    {
        System.out.println("run()方法的打印:" + 
                Thread.currentThread().getName());
    }
    
    public static void main(String[] args)
    {
        MyThread04 mt = new MyThread04();
        mt.start();
    }
    
}
静态块的打印:main
构造方法的打印:main
run()方法的打印:Thread-0

2、this.XXX() 与 Thread.currentThread.XXX()或Thread.XXX()

public class MyThread05 extends Thread
{
    public MyThread05()
    {
        System.out.println("MyThread5----->Begin");
        System.out.println("Thread.currentThread().getName()----->" + 
                Thread.currentThread().getName());//这种调用方式表示的线程是正在执行Thread.currentThread.XXX()所在代码块的线程
        System.out.println("this.getName()----->" + this.getName());//这种调用方式表示的线程是线程实例本身
        System.out.println("MyThread5----->end");
    }
    
    public void 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)
    {
        MyThread05 mt5 = new MyThread05();
        mt5.start();
    }
    
}
MyThread5----->Begin
Thread.currentThread().getName()----->main
this.getName()----->Thread-0
MyThread5----->end
run----->Begin
Thread.currentThread().getName()----->Thread-0
this.getName()----->Thread-0
run----->end