Java多线程之后台线程不执行finally

时间:2022-05-15 17:40:28

后台线程不执行finally

package wzh.daemon;

import java.util.concurrent.TimeUnit;

class ADaemon implements Runnable {

    @Override
    public void run() {
        try {
            System.out.println("Starting ADaemon");
            TimeUnit.SECONDS.sleep(1);
        } catch (Exception e) {
            System.out.println("Exiting via InterruptedException");
        } finally {
            //如果是后台线程,则finally不会被执行。
            //因为主线程退出后,后台线程就自动退出了。
            System.out.println("This should always run?");
        }
    }

}

public class DaemonsDontRunFinally {
    public static void main(String[] args) {
        Thread thread = new Thread(new ADaemon());
        thread.setDaemon(true);
        thread.start();
    }
}