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...........
Joined: Apr 04, 2005
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
Joined: Mar 22, 2005
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.
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.
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)