假设有一个流操作需要一段时间才能完成,例如:
Files.walk(FileSystems.getDefault().getPath("/usr/local"))
.mapToLong(path -> path.toFile().length())
.sum();
在单独的线程中运行时如何中断此操作?
我可以在中间操作中检查Thread.isInterrupted()
,但它看起来很混乱:
.peek(e -> {
if (Thread.currentThread().isInterrupted()) {
throw new RuntimeException("Interruption requested");
}
})
答案 0 :(得分:0)
我认为这不是一个好主意。尽管在Peek(...)
中抛出RuntimeException,这段代码永远不会离开while循环package so;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.HashSet;
public class CrazyClass {
static class RunMe implements Runnable{
@Override
public void run() {
try {
Files.walk(FileSystems.getDefault().getPath("....."))
.mapToLong(path -> path.toFile().length())
.peek(e -> {
if (Thread.currentThread().isInterrupted()) {
throw new RuntimeException("Interruption requested");
}
})
.sum();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread th = new Thread(new RunMe());
th.start();
try{
while(th.getState() == Thread.State.RUNNABLE){
th.interrupt();
Thread.sleep(100);
}
}
catch(Exception x){
}
}
}