The documentation of java.util.Timer says:
If a caller wants to terminate a timer's task execution thread rapidly, the caller should invoke the timer's cancel method.
That's what you're supposed to do. Robert Harvey linked to something that will show you how as a comment under your question.
Using your code, this printed the same thing as your code but then it quits:
public static void main(String[] args) {
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
System.out.println("hello");
timer.cancel();
}
}, 1);
System.out.println("hi");
}
Alternatively, you could make the timer a Daemon by creating it like this:
public static void main(String[] args) {
final Timer timer = new Timer(true);
timer.schedule(new TimerTask() {
public void run() {
System.out.println("hello");
}
}, 1);
System.out.println("hi");
}
The problem is this can exit before the task runs and give output like this:
hi
<exit>
The javadoc of public Timer(boolean isDaemon)
explains why:
Creates a new timer whose associated thread may be specified to run as a daemon. A daemon thread is called for if the timer will be used to schedule repeating "maintenance activities", which must be performed as long as the application is running, but should not prolong the lifetime of the application.