0

Example1 A junit test method. This will not print finally.

@Test
public void junit_Thread() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("run");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("finally");
            }
        }
    }).start();
    System.out.println("end");
}

Example2 A typical main method. This will wait for 3 seconds and print finally.

public class MainThread {
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("run");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println("finally");
                }
            }
        }).start();
        System.out.println("main thread exit");
    }
}

I want to understand why Example1 doesn't print finally as Example2 does.

  • *Example1 A junit test method. This will not print finally.* - Does it print "run"? – klutt Jun 27 '22 at 08:01
  • Does this [post](https://stackoverflow.com/questions/16616590/thread-behaving-strangely-in-junit) answer your question? – aglamp Jun 27 '22 at 08:01

0 Answers0