The right way to make java.util.Timer a daemon

I have the following java.util.Timer, but it does not seem to be running, and I do not know why.

public static void main(String[] args)
{
  Timer to = new Timer(true);

  System.out.println("Now=" + System.currentTimeMillis());
  to.schedule(new TimeOutTask("Short#1 - 250"), 250);
  to.schedule(new TimeOutTask("Long - 10050"), 10050);
  to.schedule(new TimeOutTask("Short#2 - 250"), 250);
  to.schedule(new TimeOutTask("Medium - 5050"), 5050);
  to.schedule(new TimeOutTask("Short#3 - 250"), 250);
}

Everything TimeOutTaskprints the line and the current time. When the daemon flag is false, the application does not terminate, and I see the following:

Now=1297705592543
Short#1 - 250:1297705592793
Short#3 - 250:1297705592793
Short#2 - 250:1297705592793
Medium - 5050:1297705597605
Long - 10050:1297705602605

When true, the application terminates and I see the following:

Now=1297705249422

I'm just trying to find a way to control multiple tasks for timeouts; I do not want the thread to track timeouts so that the application does not stop. So I want a demon, but when I make him a demon, none of my tasks will be completed?!?!

EDIT:

, , , . , , -, , , .

, , . , , , , .

JFrame f = new JFrame("Test Frame");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

.

+3
3

JVM main(), . , . ( ), :

import java.util.*;
import java.awt.*;
import java.awt.event.*;

public class TimerTest extends Frame implements ActionListener {
    Timer to;

    TimerTest() {
    to = new Timer(true);

        System.out.println("Now=" + System.currentTimeMillis());
        to.schedule(new TimeOutTask("Short#1 - 250"), 250);
        to.schedule(new TimeOutTask("Long - 10050"), 10050);
        to.schedule(new TimeOutTask("Short#2 - 250"), 250);
        to.schedule(new TimeOutTask("Medium - 5050"), 5050);
        to.schedule(new TimeOutTask("Short#3 - 250"), 250);

        Button b = new Button("Click to exit");
        b.addActionListener(this);
        this.add(b);
        this.pack();
        this.setVisible(true);
    }

    public static void main(String[] args) {
        TimerTest t = new TimerTest();
    }

    public void actionPerformed(ActionEvent a) {
        this.dispose();
    }
}

class TimeOutTask extends TimerTask {
    String s;

        TimeOutTask(String s) {
        this.s = s;
    }

    public void run() {
        System.out.println(s);
    }
}

, , , . ", " , . , .

+4

, , , . : , , . :)

, , , .

+5

Javas daemon Thread , . , jvm , .

, , jvm .

0

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


All Articles