Bum*_*Gee 8 java concurrency multithreading
我有一个关于Thread子类的取消策略的实现的问题.通常的做法是这样做:
class A extends Thread {
[...]
public final void run() {
try {
while(!Thread.currentThread().isInterrupted()) {
[...]
}
} catch (InterruptedException consumed) {
}
}
public final void cancel() {
interrupt();
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是关于Thread.currentThread()...为什么通常的做法是使用currentThread()来检查中断标志而不是在cancel()方法中设置它?仅仅像这样调用A的isInterrupted()方法就不够了:
while (!isInterrupted()) {
[...]
}
Run Code Online (Sandbox Code Playgroud)
我无法在Thread JavaDoc,Brian Goetz关于并发Java或stackoverflow的优秀书籍中找到答案.
提前感谢您的见解!
干杯,格奥尔格
And*_*sov 16
在你的情况下,只需要打电话就足够了,!isInterrupted()因为你正在从Thread课堂上扩展.通常你不会延伸Thread- 这就是你打电话的原因Thread.currentThread().
从 Java 5 开始,直接使用线程并不是一个好主意。您应该使用 Executor 框架并根据您的要求选择执行策略。实例isInterrupted()方法测试该线程是否已被中断。线程的中断状态不受该方法影响。内部isInterrupted()其实是一个native方法。
906 public boolean isInterrupted() {
907 return isInterrupted(false);
908 }
Run Code Online (Sandbox Code Playgroud)
使用执行器框架时,您不知道当前哪个线程实例正在执行您的代码,因此约定是使用 Thread.currentThread.isInterrupted()
| 归档时间: |
|
| 查看次数: |
10867 次 |
| 最近记录: |