当前线程

一个语句可以由不同的线程在不同的时间执行。

Thread类静态方法currentThread()返回调用此方法的Thread对象的引用。

Thread  t = Thread.currentThread();

示例:

public class Main extends Thread {
    Main(String name) {
        super(name);
    }
    public void run() {
        Thread t = Thread.currentThread();
        String threadName = t.getName();
        System.out.println("Inside run() method:  " + threadName);
    }
    public static void main(String[] args) {
        Main ct1 = new Main("First Thread");
        Main ct2 = new Main("Second Thread");
        ct1.start();
        ct2.start();
        Thread t = Thread.currentThread();
        String threadName = t.getName();
        System.out.println("Inside main() method:  " + threadName);
    }
}

运行结果:

Inside run() method:  First Thread
Inside run() method:  Second Thread
Inside main() method:  main

通过获取当前线程可使用下列方法:

getName() // 获取线程名
getPriority() // 获取线程优先级
getState() // 获取线程状态

MIT Licensed | Copyright © 2018-present 滇ICP备16006294号

Design by Quanzaiyu | Power by VuePress