1. 程式人生 > 其它 >在方法中定義一個類的寫法

在方法中定義一個類的寫法

在《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(); } }