人品不好 iteye上面问了,但是连帖子都找不到了,真心无语 第二次了,大牛们给说说我这代码啥问题,
按理说ExecutorService的shutDownNow会吧所有正在执行的任务给中断(调用interrupt), 但事实并非如此,是不是
我哪里理解错了,我对已提交的任务返回的Future调用cancel也不行,只有同时shutDownNow和cancel一起调用才可以正常退出R1
- Java code
package com.thread;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;class R2 implements Runnable { Runnable r; public R2(Runnable r) { this.r = r; } @Override public void run() { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (r) { r.notifyAll(); } System.out.println("R2 over"); }}public class R1 implements Runnable { @Override public void run() { boolean b = false; synchronized (this) { while (!(b = Thread.interrupted())) { try { wait(); System.out.println("R1 awakend"); } catch (InterruptedException e) { System.out.println("InterruptedException, interu:" + b); } } System.out.println("R1 over, interrupted:" + b); } } public static void main(String[] args) throws InterruptedException { ExecutorService exec = Executors.newCachedThreadPool(); Runnable r1 = new R1(); Future<?> f = exec.submit(r1); exec.execute(new R2(r1)); TimeUnit.SECONDS.sleep(2); exec.shutdownNow(); /*boolean ret = f.cancel(true); System.out.println("main cancel:" + ret );*/ }}
------解决方案--------------------------------------------------------
不知道LZ有没有看过Object类的wait方法的API:
抛出:
IllegalMonitorStateException - 如果当前的线程不是此对象监视器的所有者。
InterruptedException - 如果在当前线程等待通知之前或者正在等待通知时,另一个线程中断了当前线程。在抛出此异常时,当前线程的中断状态 被清除。
也就是说,从wait中断后,中断标记就被清掉了,while里的那个条件自然一直返回false
------解决方案--------------------------------------------------------
看一下这个吧:
wait
public final void wait()
throws InterruptedException在其他线程调用此对象的 notify() 方法或 notifyAll() 方法前,导致当前线程等待。换句话说,此方法的行为就好像它仅执行 wait(0) 调用一样。
当前线程必须拥有此对象监视器。该线程发布对此监视器的所有权并等待,直到其他线程通过调用 notify 方法,或 notifyAll 方法通知在此对象的监视器上等待的线程醒来。然后该线程将等到重新获得对监视器的所有权后才能继续执行。
对于某一个参数的版本,实现中断和虚假唤醒是可能的,而且此方法应始终在循环中使用:
synchronized (obj) {
while (<condition does not hold>)
obj.wait();
... // Perform action appropriate to condition
}
此方法只应由作为此对象监视器的所有者的线程来调用。有关线程能够成为监视器所有者的方法的描述,请参阅 notify 方法。
抛出:
IllegalMonitorStateException - 如果当前线程不是此对象监视器的所有者。
InterruptedException - 如果在当前线程等待通知之前或者正在等待通知时,任何线程中断了当前线程。在抛出此异常时,当前线程的中断状态 被清除。