using sleep() for a single thread
Can anyone tell me why sleeping one thread is stopping my whole
execution
to better explain your Swing GUI is created on its own special thread separate from that which main()
and other code will run in, this is done via creating your Swing components in the SwingUtilities.invokeXXX
block (even if you have not done this your GUI will be run on a single thread called the initial thread) . Now if you simply call sleep
while on Event Dispatch Thread
(or for that matter on the same Thread
) it will wait for the call to Thread.sleep
to finish. Now because all Swing events are processed on EDT we pause its execution by calling sleep(..)
thus pausing the UI events from being processed and therefore GUI is frozen (until sleep(..)
returns).
You should not use Thread.sleep(..)
on Event Dispatch Thread
(or any Thread
where sleep will cuase unwanted execution blocking), as this will cause the UI to seem frozen.
Here is a nice example which demonstrates exactly, this unwanted behavior caused by invoking Thread.sleep(..)
on GUI's EDT.
Rather use:
Swing Timer for example:
int delay=1000;// wait for second
Timer timer = new Timer(delay, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
//action that you want performed
}
});
//timer.setRepeats(false);//the timer should only go off once
timer.start();Swing Worker
or if no Swing components are being created/modified:
TimerTask
Thread, you would then use
Thread.sleep(int milis)
(but thats last option in any case IMO)
UPDATE
Swing Timer
/SwingWorker
was only added in Java 1.6, however, TimerTask
and Thread
have been around for alot longer sine Java 1.3 and JDK 1 repsectively, thus you could even use either of the 2 above methods and wrap calls that create/manipulate Swing components in SwingUtilities/EventQueue#invokeXX
block; thats the way things used to be done :P
How can I sleep one thread while the other thread is running in Java
There is no instance method Thread#sleep(long)
. In fact, you call the static method that sets the calling thread to sleeping state.(see this)
As @Kayaman sais, within this time, both threads finish, which causes your result.
Also, you should be aware that you cannot predict Threads, because they are very platform dependent and handled different on multiple Systems.
Instead, you can use the instance method Thread.join()
if you want to wait until a Thread finished.
What is the purpose of the sleep() function in a Thread?
Use of sleep()
function (and it's friends) usually indicate design flaw. The rare exceptions are sleeps used in debugging.
The common misguided usages of sleep
include an attempt to time events to a certain time (bad, because no one guarantees that sleep will take exactly that many units as prescribed on non-RT systems), attempt to wait for some events (bad, because to wait for event you should use specific waiting functions available with your threading library) or an attempt to yield resources - bad, because if you have nothing to do, just exit the thread.
How to let a thread wait itself out without using Sleep()?
While the other answer is a possible way to do it, my answer will mostly answer from a different angle trying to see what could be wrong with your code...
Well, if you don't care to wait up to one second when flag
is set to false
and you want a delay of at least 1000 ms, then a loop with Sleep
could work but you need
- an atomic variable (for ex.
std::atomic
) - or function (for ex.
InterlockedCompareExchange
) - or a
MemoryBarrier
- or some other mean of synchronisation to check the flag.
Without proper synchronisation, there is no guarantee that the compiler would read the value from memory and not the cache or a register.
Also using Sleep
or similar function from a UI thread would also be suspicious.
For a console application, you could wait some time in the main thread if the purpose of you application is really to works for a given duration. But usually, you probably want to wait until processing is completed. In most cases, you should usually wait that threads you have started have completed.
Another problem with Sleep
function is that the thread always has to wake up every few seconds even if there is nothing to do. This can be bad if you want to optimize battery usage. However, on the other hand having a relatively long timeout on function that wait on some signal (handle) might make your code a bit more robust against missed wakeup if your code has some bugs in it.
You also need a delay in some cases where you don't really have anything to wait on but you need to pull some data at regular interval.
A large timeout could also be useful as a kind of watch dog timer. For example, if you expect to have something to do and receive nothing for an extended period, you could somehow report a warning so that user could check if something is not working properly.
I highly recommand you to read a book on multithreading like Concurrency in Action before writing multithread code code.
Without proper understanding of multithreading, it is almost 100% certain that anyone code is bugged. You need to properly understand the C++ memory model (https://en.cppreference.com/w/cpp/language/memory_model) to write correct code.
A thread waiting on itself make no sense. When you wait a thread, you are waiting that it has terminated and obviously if it has terminated, then it cannot be executing your code. You main thread should wait for the background thread to terminate.
I also usually recommand to use C++ threading function over the API as they:
- Make your code portable to other system.
- Are usually higher level construct (
std::async
,std::future
,std::condition_variable
...) than corresponding Win32 API code.
Difference between wait() vs sleep() in Java
A wait
can be "woken up" by another thread calling notify
on the monitor which is being waited on whereas a sleep
cannot. Also a wait
(and notify
) must happen in a block synchronized
on the monitor object whereas sleep
does not:
Object mon = ...;
synchronized (mon) {
mon.wait();
}
At this point the currently executing thread waits and releases the monitor. Another thread may do
synchronized (mon) { mon.notify(); }
(on the same mon
object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up.
You can also call notifyAll
if more than one thread is waiting on the monitor – this will wake all of them up. However, only one of the threads will be able to grab the monitor (remember that the wait
is in a synchronized
block) and carry on – the others will then be blocked until they can acquire the monitor's lock.
Another point is that you call wait
on Object
itself (i.e. you wait on an object's monitor) whereas you call sleep
on Thread
.
Yet another point is that you can get spurious wakeups from wait
(i.e. the thread which is waiting resumes for no apparent reason). You should always wait
whilst spinning on some condition as follows:
synchronized {
while (!condition) { mon.wait(); }
}
Related Topics
Why Is Stringtokenizer Deprecated
Can't Read and Write a Tiff Image File Using Java Imageio Standard Library
How to Fix Role in Spring Security
Comparing Java Enum Members: == or Equals()
Converting Between Java.Time.Localdatetime and Java.Util.Date
Url to Load Resources from the Classpath in Java
Java - Convert Integer to String
Convert a JSON String to a Hashmap
Delete Directories Recursively in Java
How Can a String Be Initialized Using " "
Strings Are Objects in Java, So Why Don't We Use 'New' to Create Them
@Requestbody and @Responsebody Annotations in Spring
How to Get the Size of a Java.Sql.Resultset
Sparse Matrices/Arrays in Java
How to Sort List of Objects by Some Property
Why Does Changing the Returned Variable in a Finally Block Not Change the Return Value
How to Access a Value Defined in the Application.Properties File in Spring Boot