currentThread方法

currentThread方法

要点

  • public static native Thread currentThread(); 返回当前运行的线程。

curretThread()

我们直接从下面的案例直观的去看。

public class TestCurrentThreadMethod {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(
                        "run方法中打印currentThread  " + Thread.currentThread().hashCode());
            }
        });
        t1.start();
        // t1.run();
        System.out.println("main线程中打印t1对象" + t1.hashCode());
        System.out
                .println("main线程中打印currentThread " + Thread.currentThread().hashCode());
    }
}

看上面的例子中,第一次运行我们先调用t1.start();查看打印结果。你可以发现t1的hashCode和run方法中的hashCode是一致的,和main线程的Thread.currentThread().hashCode()是不一致的。第二次我们注释t1.start()开启t1.run,从“线程的创建和执行”章节中我们知道这种方式是没有真正开启一个新的线程的。再次查看结果,你可以看到run方法和main线程的Thread.currentThread().hashCode()是一样的,而t1对象的hashCode和它们不一样。第二次的t1并不是一个真正的线程就是一个普通的对象,所以它的hashCode也不可能和run方法中的一致。应为此时的run方法是在main线程中执行的。
因此我们可以知道什么叫做返回当前线程了。即Thread.currentThread()返回执行改行代码的线程的信息。


版权声明:本文为escore原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。