Why does the timer not work if we do not create a window?

Here is the code:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.Timer;

public class TimerSample {
  public static void main(String args[]) {
    new JFrame().setVisible(true);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        System.out.println("Hello World Timer");
      }
    };
    Timer timer = new Timer(500, actionListener);
    timer.start();
  }
}

It generates a window, and then periodically prints "Hello World Timer" in the terminal (Command Prompt). If I comment on this line new JFrame().setVisible(true);, the application does not print anything on the command line. Why?

ADDED:

I'm not sure I understand the answers correctly. As I understand it, the timer starts a new thread. And this new thread exists simultaneously with the "main" thread. When the "main" thread is completed (when everything is done and nothing else remains), the entire application terminates (along with the "new" thread created by the timer). Correctly?

ADDED 2:

. , , new JFrame().setVisible(true); try {Thread.sleep(20000);} catch(InterruptedException e) {}; timer.start(). , . "" , , , . new JFrame().setVisible(true); "". , (, Timer). , JFrame ?

+3
3

. , .

, , timer.start(), , .

, Thread.sleep(20000); ( ) , . - .

, JFrame, , , , , .

+5

( , , , ..). -, , .

, Frank.

+1

Timer , , .

, ( ). . , , . , . 1

, java.util.Timer javax.swing.Timer, ?

1.3 Java: java.util.Timer. , javax.swing.Timer 2

, , ... , , timer.start();, -, , , .

JFrame .

, timer, :

public static void main(String args[]) {
        //new JFrame().setVisible(true);
        ActionListener actionListener = new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                System.out.println("Hello World Timer");
            }
        };
        Timer timer = new Timer(500, actionListener);
        timer.start();
        try {
            Thread.sleep(500);//<--- the timer will still die
            Thread.sleep(100);//<--- sleep for another 100 and the timer will start printing although you can't rely on it
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
+1

Source: https://habr.com/ru/post/1737701/


All Articles