ThreadPoolExecutorthat can additionally schedule commands to run after a given delay, or to execute periodically. This class is preferable to
Timerwhen multiple worker threads are needed, or when the additional flexibility or capabilities of
ThreadPoolExecutor(which this class extends) are required.
Delayed tasks execute no sooner than they are enabled, but without any real-time guarantees about when, after they are enabled, they will commence. Tasks scheduled for exactly the same execution time are enabled in first-in-first-out (FIFO) order of submission.
Timer VS ScheduledThreadPool
According to Java Concurrency in Practice:
Timercan be sensitive to changes in the system clock,
Timerhas only one execution thread, so long-running task can delay other tasks.
ScheduledThreadPoolExecutorcan be configured with any number of threads. Furthermore, you have full control over created threads, if you want (by providing
- Runtime exceptions thrown in
TimerTaskkill that one thread, thus making
Timerdead 😦 … i.e. scheduled tasks will not run anymore.
ScheduledThreadExecutornot only catches runtime exceptions, but it lets you handle them if you want (by overriding
ThreadPoolExecutor). Task which threw exception will be canceled, but other tasks will continue to run.
If you can use
Timer, do so.
Thread_Creation creation=new Thread_Creation(“meeee”);
scheduledExecutorService.schedule(creation, 10, TimeUnit.SECONDS);
//Wiil do parallelly
Note that all the
schedule()methods return instance of
ScheduledFuturethat we can use to get the thread state information and delay time for the thread.
ScheduledFuture extends Future interface, read more about them at Java Callable Future Example.
There are two more methods in ScheduledExecutorService that provide option to schedule a task to run periodically.