如果线程的中断状态在之前或期间被设置为var_dump($session_user);
,我100%确信Thread.sleep(3000);
应该抛出InterruptedException
强>睡觉的电话。参见Calling Thread.sleep() with interrupted status set?
但是,当我事先中断线程时,仅在睡眠的3秒钟内,我从未遇到异常。怎么会这样?
这是我的代码的概念:
true
每当我在系统输出“开始睡眠”和“结束睡眠”之间中断public class MyView extends CustomComponent implements View {
private Thread importThread;
private Collection<File> allUploadFiles = new HashSet<>();
public MyView(){
allUploadFiles.add(new File("/foo/bar.xlsx"));
allUploadFiles.add(new File("/foo/bar.xlsx"));
allUploadFiles.add(new File("/foo/bar.xlsx"));
allUploadFiles.add(new File("/foo/bar.xlsx"));
createMainLayout();
}
private void createMainLayout(){
// Builds the layout here, including the upload button:
MultiFileUpload upload = new MultiFileUpload(uploadFinishedHandler, uploadStateWindow, true);
upload.setAllUploadFinishedHandler(this::allUploadFinishedHandler);
}
private void allUploadFinishedHandler(){
final UI ui = UI.getCurrent();
final VaadinSession session = VaadinSession.getCurrent();
importThread = new Thread(() -> {
UI.setCurrent(ui);
VaadinSession.setCurrent(session);
for (File uploadFile : allUploadFiles){
try {
// system output to see when the thread sleeps
System.out.print("start sleep");
Thread.sleep(3000);
System.out.print("end sleep");
MyImporter.import(uploadFile); // takes about a minute
} catch (InterruptedException e){
Thread.currentThread.interrupt(); // keep the interrupted status
System.out.print("InterruptedException thrown!");
break;
}
}
allUploadFiles.clear();
});
importThread.start();
}
/**
* this is the clickListener of the interruptImport Btn which I left out in this codesample
*/
public void interruptImport(){
importThread.interrupt();
}
}
时,都会抛出importThread
并且一切正常。
但是当我在其他任何时候中断它时,什么也没有发生,线程继续逐个文件地导入文件。 InterruptedException
可以等待3秒钟,但不会引发异常。
我不知道自己在做什么错,可能真的需要一些帮助!
编辑:按照k5_的建议,我将导入方法替换为保持忙碌状态,问题仍然存在。
然后我将此代码块添加到uploadFile-forloop 内,并且有效(编辑2:不一致,我仍然看不到原因)
Thread.sleep(3000);
但是如果我在if条件中使用Thread.currentThread()。isInterrupted()则不起作用。
为什么Thread.interrupted()起作用,但Thread.currentThread()。isInterrupted()甚至Thread.sleep(3000)不能起作用