以上内容均来自于本书和我的自己理解的总结
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类的其他方法。