Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何告诉Runnable抛出InterruptedException?_Java_Multithreading_Interrupt_Runnable - Fatal编程技术网

Java 如何告诉Runnable抛出InterruptedException?

Java 如何告诉Runnable抛出InterruptedException?,java,multithreading,interrupt,runnable,Java,Multithreading,Interrupt,Runnable,我正在编写一个调度器,它接受一个Runnable,该调度器排队等待同步或异步执行 我希望能够实现一个SomeScheduler.interrupt(int taskId),它会导致线程内抛出一个InterruptedException() 这是可能的还是我的想法完全错了?线程可以被中断,Runnable只是实现run方法的类。 就其本身而言,它不属于线程,如果要中断runnable的执行,则需要中断它的调用线程。 完成此操作的典型方法是使用执行器服务。当您向executor服务提交runnabl

我正在编写一个调度器,它接受一个
Runnable
,该调度器排队等待同步或异步执行

我希望能够实现一个
SomeScheduler.interrupt(int taskId)
,它会导致线程内抛出一个
InterruptedException()


这是可能的还是我的想法完全错了?

线程可以被中断,
Runnable
只是实现run方法的类。
就其本身而言,它不属于线程,如果要中断runnable的执行,则需要中断它的调用线程。
完成此操作的典型方法是使用
执行器服务
。当您向executor服务提交runnable或callable时,它将返回一个
未来
,然后您可以使用
未来#取消
方法中断特定任务。

请注意,简单地中断线程不会导致抛出
InterruptedException
,除非线程正在运行检查中断状态并抛出
InterruptedException
,例如
thread#sleep
方法。

我认为使用
sleep
方法时,您使用的是submit()还是execute()?看看这个问题:。Future.get()对于获取InterruptedExeception并采取纠正措施很有用。但您不能这样做,因为runnable的signature@SariefRunnable的签名中没有什么?它没有InterruptedException。因为它被选中->你不能把它添加到签名中。啊,对了,我明白你的意思了。InteruptedException不需要从Runnable冒泡出来,它只需要停止运行。Runnable中的代码需要手动检查
Thread#interrupted()
的状态,并在遇到该状态时停止/返回,或者使用类似
Thread#sleep
的方法自动执行此操作。由于您不能将异常抛出runnable,因此您可以捕获它,只要您结束线程,简单地
返回
或作为运行时异常重新抛出都不重要。是的,但这正是OP所要求的