I wanna combine a while loop with Thread.sleep, so the code will run every nanosecond or microsecond in java. Can someone help me? Sorry for my bad English, I'm Dutch.
-
1have you tried anything? show us some code you wrote to attempt this. This isn't a free coding service – ja08prat Aug 04 '17 at 16:07
-
1What exactly is the difficulty you are having? You can, indeed, invoke `Thread.sleep()` inside a `while` loop; if you tried something that did not work, then present the code. Otherwise, do try to work it out for yourself before posing a question here. – John Bollinger Aug 04 '17 at 16:08
-
I tried this:`while(something){Thread.sleep(0,1000);//I did something, with try and catch of course}`but the program freezes everytime I use that and I have to close the Window with Task Manager. – Je moder Aug 04 '17 at 16:24
-
You're not giving enough information on your problem. For all we know you could be creating a GUI program and are putting it to sleep. Please ask a more complete question including posting pertinent code **in the question itself**, not in comments, best if you could post a [mcve]. – Hovercraft Full Of Eels Aug 04 '17 at 16:51
-
What did you try so far and what did you achieve, what are you stuck at? Please note, that even though the API provides it, not every JVM will offer a nano- or microsecond timer resolution. – ijbalazs Aug 04 '17 at 16:09
-
You can also take a look at `java.util.Timer` and `java.util.TimerTask` classes which you can use to schedule your task to run every n seconds. – A0__oN Aug 04 '17 at 16:07
2 Answers
You can't sleep for a microsecond and just checking the time take many nano-seconds.
If you want to wait for a micro-second you need to busy wait. Note: this will use up to 100% CPU.
while(running) {
long end = System.nanoTime() + micros * 1000;
while (end > Systen.nanoTime()) { }
// do something.
}
so the code will run every ... microsecond in java
You might want to take into account how long the code runs for
long delayNS = micros * 1000;
long next = System.nanoTime();
while(running) {
next += delayNS;
while (next > Systen.nanoTime()) { }
// do something.
}
So if the code takes some time you have will still get consistent spacing between events.
Note:
There is Thread.sleep(long millis, int nanos)
however it just rounds off the nanos
to the nearest millis.
There is LockSupport.parkNanos(n)
which can be sub-millis but is a minimum of typically around 25 micro-seconds (even for a 1 ns delay)
There is Thread.yield()
which can take 16 microseconds, but it can also take a lot longer.

- 525,659
- 79
- 751
- 1,130
-
What do you mean with running? And is it right that micro has the value of 1? – Je moder Aug 04 '17 at 16:18
-
@DaniëlvanderZwan you can use a flag to determine how long you want to have the loop running for. If you want a 1 microseconds interval you can use `micros = 1` – Peter Lawrey Aug 04 '17 at 16:24
-
1worth mentioning in the answer that this will impact on CPU cycles, since the code is actually doing stuff all the time, it's not idle (it's the counterpart of ensuring exact timing between executuons) – albert_nil Aug 04 '17 at 16:38
You can do that inside a Thread object and in run method put your while with try catch behavior.
@Override
public void run()
{
while (true) {
try
{
for (int cont = 0; cont < numberOfRequests; cont++)
{
new GetRequestMethod(url, httpClient, defaultRequestConfig, logOption).start();
}
LOG.log(Level.INFO, "\n---------------Send REQUEST " + numberOfRequests + "---------------\n");
}
catch (OutOfMemoryError m)
{
LOG.log(Level.SEVERE, "\n\n\n\n\n\n\n\n\n\nMemory Critical Error: " + m.getMessage() + "\n\n\n\n\n\n\n\n\n\n", m);
sleep(TIME_SLEEP_EXCEPTION);
renewManager();
}
catch (Throwable t)
{
LOG.log(Level.SEVERE, "\n\n\n\n\n\n\n\n\n\nCritical Error!\n", t);
sleep(TIME_SLEEP_EXCEPTION);
renewManager();
}
}
}
sleep method:
private void sleep(int time)
{
try
{
Thread.sleep(time);
}
catch (InterruptedException e)
{
LOG.log(Level.SEVERE, "\n\n\n\n\n\n\n\n\n\nSleeping Critical Error: " + e.getMessage() + "\n\n\n\n\n\n\n\n\n\n", e);
}

- 1
- 3