I have this problem.
I need to have a method repeated endlessly, if possible,开发者_Python百科 but without overloading the system.
As I understand, while(true) { ...code... } will hang the system.
What would you suggest me to use which won't hang the system?
Thanks
Also: The execution of a my method may take up to 5 minutes, or 50 milliseconds, and I want method to be repeated jsut when it is finished
Look at Timer and TimerTask. They are exactly what you need.
Edit: Still what you need. Look at the API's
You could start a new Thread and run the task in the background. See the Java concurrency tutorial for more info.
If you only want to run 1 Thread for this task at a time, you could do it with a single thread executor.
You can use any scheduler.
e.g. QUARTZ is a good one.
You don't need a scheduler if you want a start a new repetition as soon as the first one is done, and do it on the same thread. "while (true)" is exactly the way to do this if this is actually what you want.
Your concern about 'hanging the system" indicates that either there is other stuff happening on other threads in the program, which you want to allow to happen, or that you want this sequence to end under some condition which you haven't specified.
In the second case you need to test the termination condition in the while loop instead of "while true" (or use "break"). In the first case you need to make sure other threads get access to the CPU. Calling
Thread.currentThread().yield();
for each iteration is probably the simplest way of making sure that other threads get a chance to execute.
精彩评论