The Java platform is designed to be a multithreaded environment from the outset. When your main program executes, other tasks such as fragmentation collection and event handling are done in the background. Essentially, you can think of these jobs as threads. They happen to be system-managed threads, but they are threads anyway. Threads allow you to define separate jobs that do not interfere with each other. The system will swap these jobs into or out of the CPU so that (from the outside) they appear to be running at the same time.
You can also use multiple processes when you need to work with multiple jobs in your program. These processes can be created by yourself, and you can manipulate system threads.
You do these multiple job processing, using several different classes or interfaces:
Java.util.Timer class
Javax.swing.Timer class
Thread class
Runnable interface
For a simple job, which usually needs to be repeated, you can use the Java.util.Timer class to tell it to "do it every half second." Note: Most system routines are used in milliseconds. Half a second is 500 milliseconds.
The task you want the timer to implement is defined in the Java.util.TimerTask instance, where the method that is run contains the task to be performed. These are shown in the Hi class where the string "Hi" is repeatedly displayed on the screen until you press ENTER.
import java.util.*;
public class Hi {
public static void main(String args[])
throws java.io.IOException {
TimerTask task = new TimerTask() {
public void run() {
System.out.println("Hi");
}
};
Timer timer = new Timer();
timer.schedule(task, 0, 500);
System.out.println("Press ENTER to stop");
System.in.read(new byte[10]);
timer.cancel();
}
}