java多线程读书笔记3 如何检测当前线程

以上内容均来自于本书和我的自己理解的总结

Java Threads, 3rd Edition [Book] (oreilly.com)

Sometimes, you need to find out what the current thread is.  

You can retrieve a reference to the current thread by calling the currentThread() method (a static method of the Thread class).

可以通过调用currentThread()方法(thread类的静态方法)来检索对当前线程的引用。 

 范例代码:

public class MyThread extends Thread {

    public void run( ) {

         if (Thread.currentThread( ) != this)

            throw new IllegalStateException(

                            "Run method called by incorrect thread");

         ... main logic ...

    }

}

 

Similarly, within an arbitrary object, you can use the currentThread() method to obtain a reference to a current thread. This technique can be used by a Runnable object to see whether it has been interrupted:

类似地,在任意对象中,可以使用currentThread()方法获取对当前线程的引用。可运行对象(Runnable类型对象)可以使用此技术查看其是否已被中断: 

范例代码: 

public class MyRunnable implements Runnable {

    public void run( ) {

        while (!Thread.currentThread( ).isInterrupted( )) {

            ... main logic ...

        }

    }

}

 

In fact, the Thread class includes a static method interrupted() that simply returns the value of Thread.currentThread( ).isInterrupted(), but you'll often see both uses within threaded programs.

事实上,Thread类包含一个静态方法interrupted(),

它只返回Thread.currentThread().isInterrupted()的返回值,但在线程程序中经常会看到这两种用法。 

we use the currentThread() method to obtain a thread reference in order to invoke other methods of the Thread class . 

我们使用currentThread()方法获取线程引用,以便调用thread类的其他方法。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值