execution of threads
I want to execute one thread in background executing the query, every half second (500 micro seconds) or 1 second (1000 micro seconds) depending on my requirement and I want to keep updating a variable with the value. I am not able to understand how to write this logic. Could anyone suggest me on this???
class Timer and Timer Task - often the awt / swing version .... btw it is milliseconds, not microseconds.
But I am not using swing and awt. It is core java program.
If your program is a non-GUI Java prog then Nicholas Jordan's util Timer and TimerTask answers are the correct replies here.
Your original description of the problem leads directly to the correct solution. Have one thread doing whatever it is, and spawn a second thread that calls
periodically. Use Barriers to control communications.
Thread.sleep(500); // to sleep for half a second
Yep, per ftr and Fubarable but we need to insure query(n) completes before query(n+1) and in general is approached using Barrier class, but problem as stated can lead to .....
It's somewhat potenetially complex, but for some reason is very easy and clearly obvious for me: If T-2 sleeps, then in general it cannot overrun it's own path of execution. If you try to drive the Thread with Timer and TimerTask you would have to examing the documentation for that class to insure that Timer will not fire TimerTask before previous invocation has completed.
Challenge devolves on what it is exactly you are to accomplish. If there is no GUI, then is it Polling? Some critical programing is in fact done using polling but people will tell you that it is unreliable, which is close to truth because true polling absolutely has to have realistic os for what is the system and environment that needs polling. I only use Thread.sleep(int milliseconds) and Thread.yield(); to make some or another already low-priority Thread run as control Thread - IOW not interfere with worker thread or consume system resources but instead set a boolean to false in a loop condional in the worker thread.
Polling, implemented correctly, will not run on consumer-grade operating systems nor consumer-grade hardware.
Just will not happen, caveat emptor.