方法cancel()和method interrupt()是否做重复的工作? [英] whether method cancel() and method interrupt() do the duplicate job?

查看:113
本文介绍了方法cancel()和method interrupt()是否做重复的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读 org.apache.nutch.parse.ParseUtil.runParser(Parser p,Content content)的源代码。



这两个方法调用是否做同样的事情:



指令1:

  t.interrupt(); 

指令2:

  task.cancel(真); 

org.apache.nutch.parse.ParseUtil.runParser的来源(Parser p,Content content)是:

  ParseCallable pc = new ParseCallable(p,content) ; 
FutureTask< ParseResult> task = new FutureTask< ParseResult>(pc);
ParseResult res = null;
线程t =新线程(任务);
t.start();
尝试{
res = task.get(MAX_PARSE_TIME,TimeUnit.SECONDS);
} catch(TimeoutException e){
LOG.warn(TIMEOUT parsing+ content.getUrl()+with+ p);
} catch(Exception e){
task.cancel(true);
res = null;
t.interrupt();
} finally {
t = null;
pc = null;
}
return res;


解决方案

在这里,我想弄清楚一个结论:
当我们传递true作为FutureTask.cancel()的参数时,我们可以得到与interupt()一样的效果。
为什么?
让我们来看看cancel()方法的src。
我们知道cancel()方法调用方法:

  innerCancel(mayInterruptIfRunning); 

在方法内时: innerCancel(mayInterruptIfRunning);

  if(mayInterruptIfRunning){
Thread r = runner;
if(r!= null)
r.interrupt();





$ b因此,在我的例子中,cancel()实际上调用了interrupt()的确如此。


I read the source of org.apache.nutch.parse.ParseUtil.runParser(Parser p, Content content).

Do these two method calls do the same thing:

Instruction 1:

t.interrupt();

Instruction 2:

task.cancel(true);

The source of the org.apache.nutch.parse.ParseUtil.runParser(Parser p, Content content) is:

ParseCallable pc = new ParseCallable(p, content);
FutureTask<ParseResult> task = new FutureTask<ParseResult>(pc);
ParseResult res = null;
Thread t = new Thread(task);
t.start();
try {
  res = task.get(MAX_PARSE_TIME, TimeUnit.SECONDS);
} catch (TimeoutException e) {
  LOG.warn("TIMEOUT parsing " + content.getUrl() + " with " + p);
} catch (Exception e) {
  task.cancel(true);
  res = null;
  t.interrupt();
} finally {
  t = null;
  pc = null;
}
return res;

解决方案

Here,I'd like to make up a conclusion: when we pass the true as the argument of the FutureTask.cancel(),we can get the same effect as the interupt() does yet. why? Let's peek into the src of cancel() method. we got that the cancel() method call the method:

innerCancel(mayInterruptIfRunning);

when inside the method:innerCancel(mayInterruptIfRunning);,we can have the instructions below:

if (mayInterruptIfRunning) {
                Thread r = runner;
                if (r != null)
                    r.interrupt();
            }

So,in my case,the cancel() actually call the interrupt() indeed.

这篇关于方法cancel()和method interrupt()是否做重复的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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