栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

有什么方法可以避免执行finally子句?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

有什么方法可以避免执行finally子句?

使用该

finally
块中未捕获的异常将其杀死,或者将整个JVM杀死(这将杀死线程)。

finally
除了不良的设计外,没有充分的理由停止执行块。如果不应该每次都运行它,则不要将其放在一个
finally
块中。


使用下面的测试代码,我运行了两种不同的情况,以了解杀死时会发生什么

Thread
:

  1. 启动
    Thread
    和
    sleep
    主线程2秒钟。在内
    Thread
    ,几乎立即进入该
    finally
    块,然后睡眠5秒钟。一旦主线程完成等待,终止
    Thread
    使用
    stop
    。
  2. 启动
    Thread
    并睡眠2秒钟。内
    Thread
    ,睡眠5秒进入前
    finally
    块,然后睡一些内
    finally
    给它被杀死的机会。

在第一种情况下,结果是该

finally
块停止执行。在第二种情况下,其结果是,该
finally
块完全执行,并且在
Thread
这是
stop
PED不会少。

输出(注意为所有输出添加的当前线程的名称):

thread-starting [main]trying [Thread-0]catching [Thread-0]finally-sleeping [Thread-0]thread-stopped [main] [main]thread-starting [main]trying-sleeping [Thread-1]thread-stopped [main]finally-sleeping [Thread-1]finally-done [Thread-1]

码:

public class Main{    public static void main(String[] args)    {        testThread(new TestRunnable());        println("");        testThread(new TestRunnable2());    }    private static void testThread(Runnable runnable)    {        Thread testFinally = new Thread(runnable);        println("thread-starting");        testFinally.start();        try        { Thread.sleep(2000);        }        catch (InterruptedException e)        { println("main-interrupted...");        }        testFinally.stop();        println("thread-stopped");    }    private static class TestRunnable implements Runnable    {        @Override        public void run()        { try {     println("trying");     throw new IllegalStateException("catching"); } catch (RuntimeException e) {     println(e.getMessage()); } finally {     println("finally-sleeping");     try     {         Thread.sleep(5000);     }     catch (InterruptedException e)     {         println("finally-interrupted");     }     println("finally-done"); }        }    }    private static class TestRunnable2 implements Runnable    {        @Override        public void run()        { try {     println("trying-sleeping");     Thread.sleep(5000); } catch (InterruptedException e) {     println("trying-interrupted"); } finally {     println("finally-sleeping");     try     {         Thread.sleep(5000);     }     catch (InterruptedException e)     {         println("finally-interrupted");     }     println("finally-done"); }        }    }    private static void println(String line)    {        System.out.printf("%s [%s]%n", line, Thread.currentThread().getName());        System.out.flush();    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/570189.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号