从互联网上的多篇文章中可以得知,不建议吞咽InterruptedException
。如果我要重用同一线程,使用线程池执行器会更加合理,就像这样:
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> future = executor.submit(() -> {
printNumbers(); // first call
printNumbers(); // second call
});
Thread.sleep(3_000);
executor.shutdownNow(); // will interrupt the task
executor.awaitTermination(3, TimeUnit.SECONDS);
}
private static void printNumbers() {
for (int i = 0; i < 10; i++) {
System.out.print(i);
try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // preserve interruption status
break;
}
}
}
上面的代码示例来自DZone。
但是如果每次都像这样创建新线程:
Object LOCK = new Object();
public void doSomeJob() {
myThread = new Thread(new Runnable() {
public void run() {
try {
synchronized(LOCK) {
System.out.println("Inside run");
LOCK.wait();
}
} catch(InterruptedException ignored){}
}
}
}
我还需要调用Thread.currentThread().interrupt();
吗?那样做有意义吗?
好的参考资料:
https://codepumpkin.com/interrupt-interrupted-isinterrupted-java-multithreading/
http://michaelscharf.blogspot.com/2006/09/dont-swallow-interruptedexception-call.html
synchronized(lock){...}
块。 - Victorprivate static final Object LOCK = new Object();
吗?或者至少只用final
来保护类免受错误的外部编程影响?就像我在学习时了解到的,任何线程问题都是最难找到、跟踪和测试的。 - Dirk Schumacher