有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程Java并发实践“清单7.9.在专用线程中中断任务”。调度taskThread的目的是什么。中断()?

我在实践中阅读Java并发性,遇到以下代码片段

public static void timedRun(final Runnable r,
                            long timeout, TimeUnit unit)
        throws InterruptedException {
    class RethrowableTask implements Runnable {
        private volatile Throwable t;
        public void run() {
            try { r.run(); }
            catch (Throwable t) { this.t = t; }
        }
        void rethrow() {
            if (t != null)
                throw launderThrowable(t);
        }
    }
    RethrowableTask task = new RethrowableTask();
    final Thread taskThread = new Thread(task);
    taskThread.start();
    cancelExec.schedule(new Runnable() {
        public void run() { taskThread.interrupt(); }
    }, timeout, unit);
    taskThread.join(unit.toMillis(timeout));
    task.rethrow();
}

timedRun方法用于在时间范围内运行任务r。这个功能可以通过taskThread.join(unit.toMillis(timeout));实现。那么,为什么我们需要预定的^{


共 (1) 个答案

  1. # 1 楼答案

    This feature can be implemented by taskThread.join(unit.toMillis(timeout));

    这不是真的。连接的时间限制为determines when the joining thread will give up waiting。它不会影响线程被超时限制。计划的interrupt告诉正在运行的线程在超时过期后关闭自己。如果没有它,该线程将继续消耗资源。想必这种方法的目的是防止这种情况发生