线程任务超时结束方法

import java.util.concurrent.*;

public class AsynchronousUtil {
    public static boolean waitForDone(Callable<Boolean> work, long timeout) throws InterruptedException,
            ExecutionException {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<Boolean> result = executor.submit(work);
        executor.shutdown();
        if (executor.awaitTermination(timeout, TimeUnit.MILLISECONDS) && result.isDone()) {
            Boolean done = result.get();
            if (done != null) {
                return done.booleanValue();
            }
        }
        executor.shutdownNow();
        return false;
    }

    public static <T> T waitDone(Callable<T> work, long timeout) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<T> result = executor.submit(work);
        executor.shutdown();
        if (executor.awaitTermination(timeout, TimeUnit.MILLISECONDS) && result.isDone()) {
            T done = result.get();
            if (done != null) {
                return done;
            }
        }
        executor.shutdownNow();
        return null;
    }

    public static void main(String[] args) {
//        Callable<Boolean> workNotDone = new Callable<Boolean>() {
//            @Override
//            public Boolean call() throws Exception {
//                for (int i = 0; i < 20; i++) {
//                    System.out.println("Sleep for a while Zzzzz...");
//                    Thread.sleep(1000);
//                }
//                return Boolean.TRUE;
//            }
//        };
//
//        Callable<Boolean> workDone = new Callable<Boolean>() {
//            @Override
//            public Boolean call() throws Exception {
//                for (int i = 0; i < 5; i++) {
//                    System.out.println("Sleep for a while Zzzzz...");
//                    Thread.sleep(1000);
//                }
//                return true;
//            }
//        };
//
//        try {
//            boolean resultNotDone = AsynchronousUtil.waitForDone(workNotDone, 10000);
//            System.out.println("Done: " + resultNotDone);
//
//            boolean resultDone = AsynchronousUtil.waitForDone(workDone, 10000);
//            System.out.println("Done: " + resultDone);
//
//            Boolean resultNotDoneObjectReturned = AsynchronousUtil.waitDone(workNotDone, 10000);
//            System.out.println("Done: " + resultNotDoneObjectReturned);
//
//            Boolean resultDoneObjectReturned = AsynchronousUtil.waitDone(workDone, 10000);
//            System.out.println("Done: " + resultDoneObjectReturned);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }
        testUsingFuture();
        testUsingJoin();
    }

    private static void testUsingJoin(){
        Thread t = new Thread(){
            @Override
            public void run() {
                for (int i = 0; i < 5 && !isInterrupted(); i++) {
                    System.out.println("Sleep for a while Zzzzz...");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // ignore
                        interrupt();
                    }
                }
            }
        };

        try {
            execute(t,3000);
        } catch (TimeoutException e) {
            System.out.println("超时");
        }
    }

    public static void execute(Thread task, long timeout) throws TimeoutException {
        task.start();
        try {
            task.join(timeout);
        } catch (InterruptedException e) {
            /* if somebody interrupts us he knows what he is doing */
        }
        if (task.isAlive()) {
            task.interrupt();
            throw new TimeoutException();
        }
    }

    private static void testUsingFuture(){
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<Boolean> future = executor.submit(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                for (int i = 0; i < 5; i++) {
                    System.out.println("Sleep for a while Zzzzz...");
                    Thread.sleep(1000);
                }
                return Boolean.TRUE;
            }
        });

        Boolean t = Boolean.FALSE;
        try {
            t = future.get(6, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            System.out.println("超时,结果: "+t);
            future.cancel(true);
        }finally{
            executor.shutdown();
        }

        System.out.println("正常结束,结果: "+t);
    }
}

解决线程的死掉问题和超时问题特别好使,在Java中,如果需要设定代码执行的最长时间,即超时,可以用Java线程池ExecutorService类配合Future接口来实现。 Future接口是Java标准API的一部分,在java.util.concurrent包中。Future接口是Java线程Future模式的实 现,可以来进行异步计算。 Future模式可以这样来描述:我有一个任务,提交给了Future,Future替我完成这个任务。期间我自己可以去做任何想做的事情。一段时 间之后,我就便可以从Future那儿取出结果。就相当于下了一张订货单,一段时间后可以拿着提订单来提货,这期间可以干别的任何事情。其中Future 接口就是订货单,真正处理订单的是Executor类,它根据Future接口的要求来生产产品。 Future接口提供方法来检测任务是否被执行完,等待任务执行完获得结果,也可以设置任务执行的超时时间。这个设置超时方法就是实现Java程 序执行超时的关键。 Future接口是一个泛型接口,严格的格式应该是Future,其中V代表了Future执行的任务返回值的类型。 Future接口的方法介绍如下: boolean cancel(boolean mayInterruptIfRunning) 取消任务的执行。参数指定是否立即中断任务执行,或者等等任务结束 boolean isCancelled() 任务是否已经取消,任务正常完成前将其取消,则返回true boolean isDone() 任务是否已经完成。需要注意的是如果任务正常终止、异常或取消,都将返回true V get() throws InterruptedException, ExecutionException 等待任务执行结束,然后获得V类型的结果。InterruptedException 线程被中断异常, ExecutionException任务执行异常,如果任务被取消,还会抛出CancellationException V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException 同上面的get功能一样,多了设置超时时间。参数timeout指定超时时间,uint指定时间的单位,在枚举类TimeUnit中有相关的定义。如果计 算超时,将抛出TimeoutException Future的实现类有java.util.concurrent.FutureTask即 javax.swing.SwingWorker。通常使用FutureTask来处理我们的任务。FutureTask类同时又 实现了Runnable接口,所以可以直接提交给Executor执行。使用FutureTask实现超时执行的代码如附件:FutureTaskAndExcutor.java 不直接构造Future对象,也可以使用ExecutorService.submit方法来获得Future对象,submit方法即支持以 Callable接口类型,也支持Runnable接口作为参数,具有很大的灵活性。使用示例如FutureTaskAndExcutor中的limitDemo2方法
.net C#线程超时的解决方案,使用的时候在被调线程入口调用一下这个方法就可以。更多详细代码见附件 Report.RegisterThread(Report.GetCurrentWin32ThreadID(),Thread.CurrentThread); #region 获取当取线程的ThreadID [DllImport("Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)] public static extern Int32 GetCurrentWin32ThreadID(); #endregion #region 登记访问任务线程 /// /// 访问任务线程 /// public static Hashtable TaskThreadIDTable = Hashtable.Synchronized(new Hashtable()); private static int[] TaskThreadIDs { get { int[] IDs = new int[TaskThreadIDTable.Keys.Count]; TaskThreadIDTable.Keys.CopyTo(IDs, 0); return IDs; } } public static void RegisterThread(int _threadid, System.Threading.Thread thread) { if (!TaskThreadIDTable.ContainsKey(_threadid)) TaskThreadIDTable.Add(_threadid, thread); if (!ExitInvalidThreadLoopRunning) { Thread ExitInvalidThreadLoopThread = new Thread(new ThreadStart(ExitInvalidThreadLoop)); ExitInvalidThreadLoopThread.Priority = ThreadPriority.AboveNormal; ExitInvalidThreadLoopThread.Start(); } } #endregion #region 关闭,退出超时的用户线程 private static DateTime ExitInvalidThreadLoop_LastRunTime = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0, 0)); private static bool ExitInvalidThreadLoopRunning { get { return DateTime.Now.Subtract(ExitInvalidThreadLoop_LastRunTime).TotalMinutes 10) { try { Thread thread = (Thread)TaskThreadIDTable[t.Id]; thread.Abort(); } catch { } t.Dispose(); } } #endregion } #endregion
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值