简体   繁体   English

如何在超时x次后停止任务

[英]How to stop a task after it's timed out x times

I am trying execute a runnable a few times, and if it doesn't finished within x seconds 3 times, I will cancel it. 我尝试执行一次runnable几次,如果它没有在x秒内完成3次,我将取消它。

The code I'm using to simulate the situation where the task needs to be cancelled is as follows. 我用来模拟需要取消任务的情况的代码如下。 From the output I can see that an InterruptedException was thrown and caught accordingly, but the task keeps running. 从输出中我可以看到InterruptedException被抛出并相应地捕获,但任务继续运行。

It seems that the first two times the task was run before the TimeoutException was thrown 3 times, those two runs kept on running until they are finished. 似乎在TimeoutException被抛出3次之前运行任务的前两次,这两次运行一直运行直到它们完成。 I'm wondering if there is a way to stop those two runs from completing ? 我想知道是否有办法阻止这两次运行完成?

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;
            }
        }
    }
     }
}

I don't get it what you are actually trying to simulate. 我不明白你实际上想要模拟的东西。 I would expect a simulation like paying with card (60 secs time-out to finish a task) or perhaps a secretary in a doctor-patient situation. 我希望模拟比如用卡支付(60秒超时完成一项任务)或者在医患情况下担任秘书。

The way it stand now you are creating the 5 objects in the Future. 它现在的方式是你在未来创建5个对象。 If you want more control off your threads, you should think about using synchronized methods and a monitor that handles the threads for you. 如果你想要更多地控制你的线程,你应该考虑使用synchronized方法和一个为你处理线程的监视器。

Usually when starting a thread you should go with 通常在开始一个线程时你应该去

new Thread(new Task(object or generics)).start();
Thread.sleep(2000); // calls this thread to wait 2 secs before doing other task(s)

Before doing some hardcore concurrency(multithreading), you should read some java tutorial to get some inspiration... http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html 在做一些硬核并发(多线程)之前,你应该阅读一些java教程来获得一些灵感... http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AWS Lambda:任务超时 - AWS Lambda: Task timed out Redis 命令超时; 嵌套异常是 io.lettuce.core.RedisCommandTimeoutException:命令在 1 分钟后超时 - Redis command timed out; nested exception is io.lettuce.core.RedisCommandTimeoutException: Command timed out after 1 minute(s) 完成任务后如何停止石英调度程序 - How to stop quartz scheduler after finishing a task 如何在会话超时后使Wicket中的autocompletetextfield工作 - How to make the autocompletetextfield in Wicket work after the session timed out Java中死锁或超时后如何重启事务? - How to restart transaction after deadlocked or timed out in Java ? 等待驱动程序服务器停止超时 - Timed out waiting for driver server to stop Vert.x SQLConnection:“路由中出现意外异常”,“等待30000(ms)答复后超时” - Vert.x SQLConnection: “Unexpected exception in route”, “Timed out after waiting 30000(ms) for a reply” 如何使任务x在预定任务y之后运行 - how to make a task x run after a scheduled task y 期货在[10000]毫秒后超时 - Futures timed out after [10000] milliseconds Apache HttpClient 读取一段时间后超时 - Apache HttpClient Read timed out after a while
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM