线程任务超时结束方法

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

你可能感兴趣的:(线程任务超时结束方法)