zoukankan      html  css  js  c++  java
  • 在方法中定义一个类的写法

    在《JAVA并发编程实战》这本书里,看到一种以前没有见过的写法,就是在方法里面定义一个类,这种写法太少见了,而且搜索的话也没有什么博客介绍过。在此记录一下书中给出的代码,是符合java的语法的

    public class TimedRun2 {
        private static final ScheduledExecutorService cancelExec = newScheduledThreadPool(1);
    
        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();
        }
    }
  • 相关阅读:
    2019春总结作业
    第十周作业
    第九周作业
    第八周作业
    第七周作业
    202103226-1 编程作业
    1 20210309-2 阅读任务
    1 20210309-1 准备工作
    课程总结
    第十三周总结
  • 原文地址:https://www.cnblogs.com/skyvalley/p/15362726.html
Copyright © 2011-2022 走看看