Normal thread
This is the most common, create a thread, and then let it run in the while loop, through the sleep method to achieve the effect of a timed task. This can be implemented quickly and easily, with the following code:
Public class task1 {public static void main (String[] args) { // run in a second final long timeInterval = 1000; runnable runnable = new runnable () { public void run () { while (true) { // ------- code for task to run system.out.println ("Hello !! "); // ------- ends here try { thread.sleep (timeinterval); } catch (interruptedexception e) { E.printstacktrace (); } } } &nBSP;}; thread thread = new thread (runnable); thread.start (); }}
Using a timer and TimerTask
The above implementation is very fast and easy, but it also lacks some features.
The following are the advantages of using a timer and a timertask, compared with the above methods:
When implemented, the timer class can dispatch tasks, timertask by implementing specific tasks in the run () method.
A timer instance can dispatch multiple tasks, which are thread-safe.
When a timer's constructor is called, it creates a thread that can be used to dispatch the task:
import java.util.timer;import java.util.timertask;public class task2 { Public static void main (String[] args) { timertask task = new timertask () { @Override public void run () { // task to run goes here system.out.println ("Hello !!! "); } }; timer timer = new timer (); long delay = 0; long intevalPeriod = 1 * 1000; // schedules the Task to be run in an interval timer.scheduleatfixedrate ( Task, delay, intevalperiod); } // end of main}Scheduledexecutorservice
Scheduledexecutorservice is from the Java SE 5 java.util.concurrent, as a concurrent tool class was introduced, this is the most ideal timing task implementation.
Compared to the last two methods, it has the following benefits:
-
Compared to a single thread of a timer, it performs the task in a thread pool way.
-
Can be very flexible to set the first time to execute a task delay
-
Provides a good convention to set the time interval for execution
We show this example through Scheduledexecutorservice#scheduleatfixedrate, which, through the control of the parameters in the code, adds the delay time to the first execution:
Import java.util.concurrent.executors;import java.util.concurrent.scheduledexecutorservice;import java.util.concurrent.TimeUnit;public class Task3 { public static Void main (String[] args) { Runnable runnable = new Runnable () { public void run () { // task to run goes here system.out.println ("hello !!"); } }; scheduledexecutorservice service = executors .newsinglethreadscheduledexecutor (); service.scheduleatfixedrate (runnable, 0, 1, timeunit.seconds); }}
Three ways to implement timed tasks in Java