辐射4 赵船长 导弹:a bad way simply solve the uncatched exception throw from a thread

来源:百度文库 编辑:九乡新闻网 时间:2024/04/30 15:13:05
import java.util.concurrent.*;

/**
 * InterruptBorrowedThread
 *


 * Scheduling an interrupt on a borrowed thread
 *
 * @author Brian Goetz and Tim Peierls
 */
 //don't do this way to cancel a thread even if it's a simply way to solve the uncatched exception.
public class TimedRun1 {
    private static final ScheduledExecutorService cancelExec = Executors.newScheduledThreadPool(1);

    public static void timedRun(Runnable r,
                                long timeout, TimeUnit unit) { //3-0
        final Thread taskThread = Thread.currentThread();
        cancelExec.schedule(new Runnable() {
            public void run() {
                taskThread.interrupt();//2-0
            }
        }, timeout, unit);
        r.run();//1-0
    }
}
/**
简单的处理线程抛出一个未经检查的异常的问题,应为异常会在这里 1-0 抛出,这样调用TimeRun1的调用线程
本身就能捕获这个异常。

但是缺点:
1.任意线程可以调用这个方法来中断,但是我们就不可能了解这个调用者线程的中断策略。
2.如果任务在限时之前就完成了任务,1-0 返回,2-0 schedule的中断会在返回后执行中断,而这时线程已经完成,
到底发生了什么,执行了什么,我们并不知道,结果一定不好。
3.如果任务不响应中断, 1-0一直在运行,timedRun 3-0 方法不会返回,直到这个任务完成为止。 这时可能已经超时
很久了,或者还没有到限定时间,但是发生过中断,缺没有结果,这会惹恼用户的。
*/