Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Simple Thread Question

 
nikunj shingala
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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...........


Thanks
 
Alan Mehio
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ulf,
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
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic