Java 取消无限循环
我想在我的应用程序中加载一个文件。我遇到的问题是,加载该文件可能需要无限长的时间。Java 取消无限循环,java,Java,我想在我的应用程序中加载一个文件。我遇到的问题是,加载该文件可能需要无限长的时间。 我想允许用户取消一个文件,如果他们想停止加载到系统。在文件停止加载后,我希望直接在同一线程中执行代码 我写了一个简单的例子来说明如何做到这一点。我的解决方案是为代码提供一个嵌套线程,该线程可以无限期加载。如果用户取消,则会中断线程 public class InfiniteLoopTest { public static void main(String args[]) throws Interrupt
我想允许用户取消一个文件,如果他们想停止加载到系统。在文件停止加载后,我希望直接在同一线程中执行代码 我写了一个简单的例子来说明如何做到这一点。我的解决方案是为代码提供一个嵌套线程,该线程可以无限期加载。如果用户取消,则会中断线程
public class InfiniteLoopTest {
public static void main(String args[]) throws InterruptedException
{
final Thread[] innerThread = new Thread[1];
final Thread outerThread = new Thread(new Runnable(){
@Override
public void run() {
innerThread[0] = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
// Load in the file here (Never finishes)
loadFile();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
});
innerThread[0].start();
// Wait for the thread to complete
try
{
innerThread[0].join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
// Code that must always be called whether the file isn't loaded or not
System.out.println("Do something after loading the file");
}
});
outerThread.start();
// Wait 5 seconds then simulate the user cancelling loading the file
Thread.sleep(5000);
innerThread[0].interrupt();
}
}
我遇到的问题是,我希望使用executor服务,而不是只使用线程,如果有任何问题,我会传递异常。这意味着,尽管这个解决方案可行,但最终会变得相当混乱,并且不易维护
可以避免嵌套线程吗 添加一个可从两个线程访问的
boolean
参数,并在循环时将其传递给。当用户单击“更改其值”时,循环将停止并在其之后继续执行代码。您可以使用finally{}
块来避免嵌套线程:
final Thread t = new Thread(() -> {
try {
loadFile();
} catch (InterruptedException ex) {
ex.printStackTrace();
} finally {
// Code that must always be called whether the file isn't loaded or not
System.out.println("Do something after loading the file");
}
});
t.start();
// Wait 5 seconds then simulate the user cancelling loading the file
Thread.sleep(5000);
t.interrupt();
while
循环相当于无限加载文件。我无法更改这段代码,因为它与调用名为loadFile()
或类似的方法相同。这是一个无限期加载代码的示例。您必须中断长时间运行的任务。。。碰巧加载文件发生在有限的缓冲区中,因此,您只需检查缓冲区读取之间的取消。还可以查看CompletableFuture
类,它是一个很好的任务抽象,您可能希望在任务完成之前强制完成该任务。问题是我正在使用Apache POI来处理XLS文件等文件。尝试解码这些块,直到完成。如果我只是用一个缓冲区读取文件,那么你的方法会起作用,但问题不只是读取它们,还包括处理它们。如果在最后一次中断异常期间抛出另一个会发生什么?我想要在finally中使用的代码可能需要一些时间才能完成。另外,如果没有线程,我不相信可以抛出中断异常。try
块中的sleep
。你是说System.out.println(“加载后做某事…”)中的代码也可以被用户中断?什么会引发中断异常?顺便说一句:t.interrupt()本身的调用只会在线程中设置一个“interrupted”标志。在
loadFile()`-方法中,您的任务是检查线程是否被中断,然后抛出InterruptedException。您在那里的代码是否编译?如果loadFile
没有抛出InterruptedException
,那么它就不应该编译。否则,如果它可以像这样工作,那么我可以存储一个布尔值
,表示加载文件后它不能被中断。