java替代Thread.stop()中断特定的调用 [英] java alternative Thread.stop() to interrupt specific call

查看:73
本文介绍了java替代Thread.stop()中断特定的调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来告知此电话,这大约需要20-120秒:

I am searching for a way to tell this call, which takes about 20-120 seconds:

final Area image = ...
final AffineTransform transform = new AffineTransform();
transform.scale...
image.transform(transform); //this specific line takes that long

如果调用Thread.interrupt()则停止;

to stop if Thread.interrupt() is called;

因为我只想调用一次,所以我无法在while(Thread.currentThread.isInterrupted())循环中运行某些东西并抛出InterruptedException.我可以在调用前后运行isNotInterrupted,但是仍然如何停止此行代码?

Because I just want to call that once, I cannot run some stuff in a while(Thread.currentThread.isInterrupted()) loop and throw an InterruptedException. I can run if isNotInterrupted before and after the call, but still, how to stop this line of code??

推荐答案

Java中的线程中断是协作的.

Thread interruption in Java is cooperative.

但是我相信你明白这一点.如果您的仿射变换花了这么长时间才能运行,并且您尝试一口气运行它甚至不检查中断标志,您的变换就会很愉快地进行变换.

But I believe you understand that. If your affine transform takes that long to run and you try and run it in one go without even checking for the interrupted flag, your transform will happily transform along.

没有 Thread.kill().

您别无选择.请注意,我不知道是否可能,但理想情况下,应该将这样一个运行时间较长的线程拼接为可管理的可定时块,并检查这些块之间的中断标志.

You have no choice. Note that I don't know whether it is possible but ideally such a long running thread should be spliced into manageable timeable chunks and the interrupt flag checked between these chunks.

当然,您还可以选择在当前线程中运行该转换,而是在 ExecutorService 中运行,并获取 Future 结果;并且您会 .get()超时.

Of course, you also have the option to not run that transform in the current thread but in an ExecutorService instead, and grab a Future of the result; and you would .get() with timeout.

但是最终的问题仍然存在:您必须检查中断标志.并且您将必须处理 .get()上的 TimeoutException .

But the end problem will remain: you MUST check for the interrupt flag. And you will have to deal with a TimeoutException on .get().

好的,我在数学上很烂.但是,这种转换不能分成几个线程吗?例如,您不能使用fork/join框架吗?还是更好,如果您使用Java 8,则 Stream Collector ?

OK, I suck at math. But can't this transform be split in several threads? Can't you use, for instance, the fork/join framework? Or better yet, if you use Java 8, a Stream and a Collector?

这篇关于java替代Thread.stop()中断特定的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆