Java长时间运行任务线程中断与取消标志 [英] Java long running task Thread interrupt vs cancel flag

查看:30
本文介绍了Java长时间运行任务线程中断与取消标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个长时间运行的任务,例如:

I have a long running task, something like:

public void myCancellableTask() {
    while ( someCondition ) {
       checkIfCancelRequested();
       doSomeWork();
    }
 }

可以取消任务(请求取消并且 checkIfCancelRequested() 检查取消标志).通常,当我编写这样的可取消循环时,我使用一个标志来指示已请求取消.但是,我知道我也可以使用 Thread.interrupt 并检查线程是否已被中断.我不确定哪种方法是首选方法,为什么,想法?

The task can be cancelled (a cancel is requested and checkIfCancelRequested() checks the cancel flag). Generally when I write cancellable loops like this, I use a flag to indicate that a cancel has been requested. But, I know I could also use Thread.interrupt and check if the thread has been interrupted. I'm not sure which would be the preferred approach and why, thoughts?

谢谢,

杰夫

推荐答案

中断会将线程从指定的等待条件列表中炸出.您自己的取消标志不会.如果要中断对 IO 和事件的等待,请使用中断.否则使用你自己的.

Interrupt will blast the thread out of a list of specified wait conditions. Your own cancel flag will not. If you want to interrupt waits on IO and events, use interrupt. Otherwise use your own.

这篇关于Java长时间运行任务线程中断与取消标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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