I wrote like this.
public static void main(String[] args){ Thread thread = new Thread(() -> { while(true){ try{ // do something Thread.sleep(10); }catch(InterruptedException ex){ System.out.println("ABC"); break; } } }); JFrame frame = new JFrame(); frame.setSize(1280,720); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.addWindowListener(new WindowAdapter(){ @Override public void windowClosed(WindowEvent e){ thread.interrupt(); } }); thread.start(); frame.setVisible(true); }
When I clicked the close button on the window,
The program took several seconds to finish.
What prevents the exit of the program? And how can I close the program right away without using JFrame.EXIT_ON_CLOSE ?
I think my thread ( while(true) thread) ends immediately
because "ABC" is displayed shortly after clicking the close button.
Thanks.
EDIT
The same thing happened without my flow.
public static void main(String[] args){ JFrame frame = new JFrame(); frame.setSize(1280,720); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setVisible(true); }
EDIT2
public static void main(String[] args){ Runtime.getRuntime().addShutdownHook(new Thread(() -> { Thread[] threads = new Thread[5]; Thread.enumerate(threads); System.out.println(Arrays.toString(threads)); System.err.println(LocalDateTime.now() + " SHUTDOWN"); } )); JFrame frame = new JFrame(); frame.setSize(1280,720); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.addWindowListener(new WindowAdapter(){ @Override public void windowClosed(WindowEvent e){ Thread[] threads = new Thread[5]; Thread.enumerate(threads); System.out.println(Arrays.toString(threads)); System.err.println(LocalDateTime.now() + " CLOSE"); } }); frame.setVisible(true); }
the conclusion was:
[Thread[AWT-EventQueue-0,6,main], Thread[DestroyJavaVM,5,main], null, null, null] 2016-08-02T19:04:50.465 CLOSE [Thread[DestroyJavaVM,5,main], Thread[Thread-0,5,main], null, null, null] 2016-08-02T19:04:51.762 SHUTDOWN