File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Simple Thread Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Simple Thread Question" Watch "Simple Thread Question" New topic

Simple Thread Question

nikunj shingala
Ranch Hand

Joined: Jul 20, 2009
Posts: 30

I am new in Thread and I never use a thread now i want that my same code will be automatically executed after every 15 second now how can i use thread in it...please give me example...... or any other way same code executed after some time...........

Alan Mehio
Ranch Hand

Joined: Apr 04, 2005
Posts: 73
Usually periodic execution of a task can be done by using sleep in your run or you can use ScheduledExecutorService which is more preferred things to do.

The first one is better for you to understand the concept.

Please let me know if you want the other approach or if you have any further question. Always it is better not to extend a thread and implement Runnable which is done above for many reasons.

Hope this could help

Alan Mehio
London, UK
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
Periodic execution of tasks is better scheduled using the java.util.Timer and TimerTask classes than by starting a thread and then putting it to sleep.

Also see ExtendingThreadVsImplementingRunnable
Alan Mehio
Ranch Hand

Joined: Apr 04, 2005
Posts: 73
Thanks for your valuable comments. Actually my post was based on explaining the idea of the periodic thread running in a very simple view to allow for understanding the concept without using a thread part. The second point I want to stress on is the usage of java.util.Timer; the Timer has a draw back which is there is only one thread that execute the TimerTask hence if the timer task takes too long to run, the timing accuracy of other Timer Tasks can suffer; for example, if the recurring TimerTask is scheduled to execute every 20 ms and another TimerTask takes 40 ms to run, hence, the recurring tasks get called twice which will will have different consequences.

As a result, it is better to use ScheduledThreadPoolExecutor for periodic task execution.

Krum Bakalsky
Ranch Hand

Joined: Mar 14, 2010
Posts: 46
You say you just want some piece of code executed regularly (periodically) ?
Why use threads at all ?

Use job scheduling instead . A possible elegant solution is the open source Java job scheduler Quartz. It abstracts you from threads entirely.
What's the point of making things complex when they could be simple...

SCJP 6 (86% - the hard way), SCBCD 5 (81% - the hard way)
I agree. Here's the link:
subject: Simple Thread Question
It's not a secret anymore!