我正在尝试执行一次runnable,如果它没有在x秒内完成3次,我将取消它。
我用来模拟需要取消任务的情况的代码如下。从输出中我可以看到InterruptedException被抛出并相应地捕获,但任务继续运行。
似乎在TimeoutException被抛出3次之前运行任务的前两次,这两次运行一直运行直到完成。我想知道是否有办法阻止这两次运行完成?
public class SomeClass {
private static int c =0;
public static void main(String[] args){
Runnable dummyRunnable = new Runnable() {
@Override
public void run() {
System.out.println("Hello from dummyRunnable!");
for (int i =0; i< 10; i++){
try {
//simulate work here
if (!Thread.currentThread().isInterrupted()) Thread.sleep(5000);
System.out.println("thread sleeps for the " + i + " time!");
} catch (InterruptedException ie){
System.out.println("InterruptedException catched in dummyRunnable!");
//Thread.currentThread().interrupt(); //this has no effects
break;
}
}
}
};
BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(10 * 3, true);
ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3, Long.MAX_VALUE, TimeUnit.MILLISECONDS, blockingQueue);
for (int i =0; i< 5; i++){
Future<?> task = executor.submit(dummyRunnable);
try{
Thread.sleep(1000);
task.get(2000, TimeUnit.MILLISECONDS);
} catch (TimeoutException te){
c++;
System.out.println("TimeoutException from a task!");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (c==3){
System.out.println("cancelling task...");
task.cancel(true);
break;
}
}
}
}
}
答案 0 :(得分:0)
我不明白你实际上想要模拟的东西。我希望模拟比如用卡支付(60秒超时完成一项任务)或者在医患情况下担任秘书。
现在的方式就是在未来创建5个对象。 如果你想要更多地控制你的线程,你应该考虑使用synchronized方法和一个为你处理线程的监视器。
通常在启动线程时,您应该使用
new Thread(new Task(object or generics)).start();
Thread.sleep(2000); // calls this thread to wait 2 secs before doing other task(s)
在做一些硬核并发(多线程)之前,你应该阅读一些java教程来获得一些灵感...... http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html