How to pause a thread in java? - java

Consider the following code:
while(true) {
someFunction();
Thread.sleep(1000);
}
What I want is that, someFunction() be called once every 10 seconds. But this is not the case. It is being called every second. I tried Thread.wait(1000), but even that doesnt help. I removed of the while part, just kept the body, and at the end wrote :
Thread.start();
But it throwed an exception. Is there any other solution to this?

It's being called every second because you're sleeping for 1000 milliseconds, aka 1 second.
Change it to Thread.sleep(10000) and that'll be better for you.
Alternatively, use
Thread.sleep(TimeUnit.SECONDS.toMillis(10));
which means you don't have to do the arithmetic yourself. (Many APIs now take a quantity and a TimeUnit, but there doesn't appear to be anything like that for Thread.sleep unfortunately.)
Note that this will make the thread unresponsive for 10 seconds, with no clean way of telling it to wake up (e.g. because you want to shut it down). I generally prefer to use wait() so that I can pulse the same monitor from a different thread to indicate "I want you to wake up now!" This is usually from within a while loop of the form
while (!shouldStop())
EDIT: tvanfosson's solution of using a Timer is also good - and another alternative is to use ScheduledExecutorService which can be a bit more flexible (and easier to test).

Thread.sleep() takes the number of miliseconds to sleep. Thus, calling Thread.sleep(1000) sleeps 1000 miliseconds, which is 1 second. Make that Thread.sleep(10000) and it will sleep 10 seconds.

1 second is 1000 milliseconds, so if you want 10 seconds = 10 * 1000 = 10000 milliseconds
e.g.
try {
long numMillisecondsToSleep = 5000; // 5 seconds
Thread.sleep(numMillisecondsToSleep);
} catch (InterruptedException e) { }

What you probably want to do is use a Timer and set up a scheduled invocation of the function rather than sleeping. If you need more exactness with regard to the interval, you can keep track of how long it has been since the last run and adjust the new timer to keep your interval from drifting. See an example of a simple timer in this tutorial.
I won't go into detail about the issue with regard to the precision of the argument, since #Jon has already covered that -- you need milliseconds rather than seconds.

Consider 1000 milliseconds is 1 second. For that you should use Thread.sleep(10000) for acheiving pause your thread in 10 seconds. You can also use looping with how many seconds to wait your thread.
Ex. suppose you want to pause your thread in half-an-hour( 30 minutes). Then use,
for(i=0;i<1800;i++)
{
Thread.sleep(1000);
}
It will pause your thread in 30 minutes.

What I want is that, someFunction() be
called once every 10 seconds.
Then why do you call Thread.sleep() with 1000 as parameter? That's in milliseconds, so you're explicitly saying "wait 1 second".

Related

Java sleep only one object

I have a program, where there are some dots flying on a screen.
I need to do something where one dot is sleeping for 2 seconds.
public void move(Dot dot) {
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
fun();
}
Sleep cause the whole program stops for 2 seconds. How to do it for only one dot?
I would change my Dot class to include a Timer. The move function could then decide based on some parameters if the Timer should be activated. Upon the first tick, disable the Timer. The Timer could set a Boolean which is queried when deciding whether moving the dot is allowed or not.
Timer Class
If I'm understanding your question correctly, your game looks something like this:
move(dot1); // You want this to move instantly
move(dot2); // You want this dot to sleep for 2 seconds, and then move
move(dot3); // You want this dot to move instantly
The thing with program execution is that everything happens in order, one line of code after the other. So move(dot2) will only get executed once move(dot1) has finished, and move(dot3) will only get executed once move(dot2) has finished. In your example, you've changed move(dot2) to sleep for 2 seconds, which means that move(dot2) will only complete 2 seconds later, which means that move(dot3) will only start 2 seconds later, once move(dot2) has finished. In fact, because the entire rest-of-the-program only resumes once move(dot2) has finished, the entire program will sleep for 2 seconds like you mentioned.
However, there is exception to this. Everything mentioned above is only applicable for a single thread. Within a thread, all code will get executed sequentially, one after the other. However, if you create multiple threads, and give each thread a different piece of code to run, all the different threads will run in parallel. Even if Thread-A hits a piece of code that takes a long time to run (such as Thread.sleep(1000)), Thread-B will still be able to run its code without waiting around.
This is a powerful feature that can be applied to your game. You want move(dot2) to sleep for 2 seconds before moving, but you don't want the rest of the game to wait around for the 2 seconds. Solution: kick off a new thread, tell it to run move(dot2), and you main thread can immediately start executing the rest of your code.
Example:
move(dot1); // will complete instantly
new Thread(() -> move(dot2, 2000)).start(); // Creates a new thread, tells it to execute move(dot2, 2000), and start it off
move(dot3); // will complete instantly, as soon as move(dot2...) has been started off, without waiting for it to finish
Some more details about Java multi-threading
P.S. You mentioned a 2 second sleep, but your code is hard-coding the sleep to 1000ms, which is 1 second. If you want it to sleep for 2 seconds, you should change it to 2000ms.
Also, if you want some dots to move instantly and others to wait for 2 seconds, you should convert the 2000 into an input argument. That way, you can call move(dot1, 0) so that it will finish instantly, and move(dot2, 2000) so that it will finish after 2 seconds.
I think your problem is you're calling sleep() in your application-thread. If you do this your whole application is stopping for two seconds.
You could start a new Thread in which you're controlling your dot. Something like that:
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// control, move your dot or sleep here
}
});
t.start();

Does Thread.sleep() make the execution to cease for accurate an interval

Here is my code
try{
System.out.println("Before");
thread.sleep(10000);//sleep for 10000 ms
System.out.println("After");
}
catch(ItrerruptedException ie){
//If this thread was intrrupted by nother thread
}
I just want to know whether the thread will sleep for exaclty 10 seconds and then print After or there is some delay?
From the javadocs: Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. Which means it will sleep for at least 10 seconds. It may sleep longer if the scheduler decides to not let it run after the 10 seconds is over.
Which may happen if more concurrent threads are in the runnable pool at the same time.
A non realtime scheduler won't guarantee timing.
If you are doing some kind of hardware communication that really relies on timing, you should probably use RTSJ.
If you are doing something each x milliseconds, you could use a TimeTask that will perform slightly better.
It will sleep for at least 10 seconds, and wake shortly after (unless interrupted). How soon after depends on the OS and the load on the machine.
It's more or less random because your OS task scheduler is usually not required to give your process all the attention it wants. Usually, you will not be able to sleep for very small amounts of time (for example, Thread.sleep(5) might resume your process later than 5 ms after the call), but as you increase the sleep time, the relative precision increases.
If you can tolerate some leeway, Thread.sleep(10000) will usually sleep for an amount of time that's close enough to 10 seconds.
I would say unless you have lots of threads running it's pretty close to exact. If you have several threads then it's a competition.
The overhead of the thread from sleep to running is very low.

How to ensure a Thread won't delay in Java?

I wrote a multi threading programme, which have two to four thread at the same time.
One of the thread is time critical thread, it will be called every 500 milliseconds, it is not allow to delay more than 10 milliseconds. But when other thread have more loading, I find that some delay, around two millisecond is occurred. (Print the timestamp to show it) So, I worry that after running for a long time it will delay more than 10 milliseconds, except from check the timestamp, and adjust the looping interval to make sure the time is not delay more than 10 milliseconds, is there any way to make it safe?
Thanks.
Sounds like you need Real-Time Java
If timing is critical, I use a busy wait on a core which is dedicated to that thread. This can give you << 10 micro-second jitter most of the time. Its a bit extreme and will result in the logical thread not being used for anything else.
This is the library I use. You can use it to reserve a logical thread or a whole core. https://github.com/peter-lawrey/Java-Thread-Affinity
By using isolcpus= in grub.conf on Linux you can ensure that the logical thread or core is not used for any else (except the 100 Hz timer and power management which are relatively small and < 2 us delay)
You can set your threads priorities:
myCriticalThread.setPriority(Thread.MAX_PRIORITY);
otherThread.setPriority(Thread.NORM_PRIORITY); // the default
yetAnotherThread.setPriority(Thread.MIN_PRIORITY);
It won't really guarantee anything though.
There is no guarantee that your thread isn't delayed, because the OS may decide to give other processes precedence (unless you put effort in setting up a complete real-time system including a modified OS). That being said, for basic tasks, you should use a ScheduledExecutorService like this:
class A {
private final ScheduledExecutorService exe = Executors.newScheduledThreadPool(1);
public void startCriticalAction(Runnable command) {
this.exe.scheduleAtFixedRate(command, 100, 100, TimeUnit.MILLISECONDS);
}
public void shutdown() {
this.exe.shutdown();
}
}
The executor service will do its best to execute the task every 100ms. You should not develop this functionality yourself, because a lot of things can go wrong.
Creep up on the timeout:
waitFor(int timeout)
{
dateTime wallTimeEnd;
wallTimeEnd=now()+(msToDateTime(timeout));
int interval=timeout/2;
while(true){
if(interval>10){
sleep(interval);
interval=dateTimeToMs(wallTimeEnd-now()) / 2;
}
else
{
do{
sleep(0);
interval=dateTimeToMs(wallTimeEnd-now());
}while(interval>0);
}
}
This only wastes a core for 5-10ms

Preferred way of waiting on two ExecutorServices?

I have two ExecutorServices, one to hold producers and the other one to hold consumers. I'm using the awaitTermination method, which is blocking and needs a timeout parameter. But I want to wait on both ExecutorServices with the same timeout. As the awaitTermination call is blocking, I can't do:
this.producersExecutorService.awaitTermination(4, TimeUnit.HOURS);
this.consumersExecutorService.awaitTermination(4, TimeUnit.HOURS);
Because that would, eventually, wait for a total of 8 hours. What should I do?
If you're waiting for both of them, just await either of them with a timeout of 4 hours, then await the other one with however much time is remaining. How you determine that is up to you - I'd probably work out the desired end time based on the current time before the first call to awaitTermination, and then work out the remaining time based on the difference between that and the current time.
It's not clear from the documentation what happens if you pass in a negative time - you should probably investigate that, and potentially take precautions (e.g. if the first call finishes at exactly the timeout, and then you end up computing the second timeout a millisecond later).

Constantly checking a port without a while loop

In a program (Java) I'm making I need to check for a specific pin in the parallel port. Whenever that pin goes from logical 0 to 1 (a positive edge clock) I have to read the data on the port and save it. This happens about every 10ms but can vary a little.
To do this I made a separate thread with a while loop that is constantly checking the port, but this makes the processor go nuts and I know it's because of the while loop. My question is, how can I constantly scan the port without using a processor intensive while loop? The program doesn't know precisely when a pin change will happen, only that it happens around every 10ms.
Fire a thread which is scheduled to execute the given Runnable at a fixed rate. You can use Timer#scheduleAtFixedRate() or ScheduledExecutorService#scheduleAtFixedRate() for this. The last one is preferred.
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new PortScanner(), 0, 10, TimeUnit.MILLISECONDS); // Run every 10 ms.
Where PortScanner can look like this:
public class PortScanner implements Runnable {
#Override
public void run() {
// Scan port here.
}
}
Don't forget to call scheduler.shutdown() at the moment your application exits, else the thread may hang.
There might be a better solution, but worst case you could just Thread.sleep for 1-2ms every iteration of the while loop.
It is really tricky to catch hardware interrupts when your code is not running as a part of operating system. What you can do is to put Thread.Sleep ( 5 ). This will sleep for 10 milliseconds, and will let the other threads run or just keep CPU idle and cool. Having 5 ms delay should be enough to ensure won't miss any clock ticks.
This would work when your clock is alternating between 10 ms high and 10 ms low. For other patterns you have to adjust the parameter accordingly.

Categories

Resources