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 "close" button of the window,
the program took few seconds to end.
What prevents program from exiting ?
And how can I close program immediately without using JFrame.EXIT_ON_CLOSE
?
I think my thread (while(true)
thread) ends immediately
because "ABC" is displayed soon after I clicked "close" button.
Thank you.
EDIT
same thing occured without my thread.
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 output 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