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()返回执行改行代码的线程的信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值