java 设置任务超时时间

转自:https://blog.youkuaiyun.com/ithouse/article/details/78257418

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;


public class TimeoutTest {
    private static ExecutorService executorService = Executors.newSingleThreadExecutor();

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        long start = System.currentTimeMillis();
        String result = timeoutMethod(5000);
        System.out.println("方法实际耗时:" + (System.currentTimeMillis() - start) + "毫秒");
        System.out.println("结果:" + result);

        try {
            Thread.sleep(8000);
            long start1 = System.currentTimeMillis();
            String result1 = timeoutMethod(5000);
            System.out.println("方法实际耗时:" + (System.currentTimeMillis() - start1) + "毫秒");
            System.out.println("结果:" + result1);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    /**
     * 有超时时间的方法
     * @param timeout
     * @return
     */
    private static String timeoutMethod(int timeout) {
        String result = "默认";
        FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {

            @Override
            public String call() throws Exception {
                return unknowMethod();
            }
        });

        executorService.execute(futureTask);
        try {
            result = futureTask.get(timeout, TimeUnit.MILLISECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            //e.printStackTrace();
            futureTask.cancel(true);
            result = "默认";
        }

        return result;
    }

    /**
     * 这个方法的耗时不确定
     * @return
     */
    private static String unknowMethod() {
        Random random = new Random();
        int time = (random.nextInt(10) + 1) * 1000;
        System.out.println("任务将耗时: " + time + "毫秒");
        try {
            Thread.sleep(time);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return "获得方法执行后的返回值";
    }

}

 

ThreadPoolTaskExecutor是Spring框架中的一个线程池实现类,可以通过设置TaskExecutor的属性来设置任务超时时间。具体方法如下: ```java ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(2); // 核心线程数 executor.setMaxPoolSize(3); // 最大线程数 executor.setKeepAliveSeconds(30); // 线程空闲时间 executor.setQueueCapacity(10); // 阻塞队列大小 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略 executor.setAwaitTerminationSeconds(60); // 等待所有任务执行完毕的时间 executor.setWaitForTasksToCompleteOnShutdown(true); // 是否等待所有任务执行完毕后再关闭线程池 executor.setTaskDecorator(new TimeoutTaskDecorator(30)); // 设置任务超时时间为30秒 executor.initialize(); // 初始化线程池 // 往线程池中添加任务 for (int i = 0; i < 5; i++) { executor.execute(new MyTask()); } // 扩大线程池 executor.setCorePoolSize(3); // 每三秒往线程池中添加一个任务 for (int i = 0; i < 15; i++) { Thread.sleep(3000); executor.execute(new MyTask()); } // 等待所有任务执行完毕 executor.shutdown(); executor.awaitTermination(60, TimeUnit.SECONDS); // 获取线程池中存活的线程数 int activeCount = executor.getActiveCount(); System.out.println("线程池中存活的线程数:" + activeCount); ``` 其中,TimeoutTaskDecorator是一个自定义的任务装饰器,用于设置任务超时时间。代码如下: ```java public class TimeoutTaskDecorator implements TaskDecorator { private int timeout; public TimeoutTaskDecorator(int timeout) { this.timeout = timeout; } @Override public Runnable decorate(Runnable runnable) { return new TimeoutRunnable(runnable, timeout); } private static class TimeoutRunnable implements Runnable { private Runnable runnable; private int timeout; public TimeoutRunnable(Runnable runnable, int timeout) { this.runnable = runnable; this.timeout = timeout; } @Override public void run() { Future<?> future = null; try { future = Executors.newSingleThreadExecutor().submit(runnable); future.get(timeout, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } finally { if (future != null) { future.cancel(true); } } } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值