Java thread in wait state

Java Wait for thread to finish

I have a thread downloading data and I want to wait until the download is finished before I load the data. Is there a standard way of doing this? More Info: I have a Download class that gets data from a URL (Serialized POJOs). Download is Runnable and Observable. It keeps track of the bytes downloaded and download size. I have a progress bar that displays the progress to the User. The GUI observes Download to update the progress bar. When the POJO is downloaded I want to get it and move to the next step. Each step has to wait for the previous to finish. The problem is I cant think of a way to pause my application to wait for the download thread. Once the download is finished I want to call download.getObject() which will return the data as an object. I can then cast it and get on with the next download. I have a helper class that manages the URLs for download and makes all of the calls to Download. This call will call getObject and do the casting. The Gui calls helper.getUser() . helper starts the thread running and I want it to ‘know’ when it is finished so it can return the casted object. Any suggestions/examples? I am in the beginning stages of this design so I am willing to change it. Update: I followed http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html#get and used modal to block until the thread finished. The code was very messy and I don’t like this approach. I will keep trying to find a ‘clean’ way to handle the workflow of the download processes.

9 Answers 9

Thread has a method that does that for you join which will block until the thread has finished executing.

I tried join() but that kept the GUI from updating. The reason I used a Thread was to keep the gui updating while the download was occurring. Calling join stops that from happening.

join() will work. if the GUI stops updating, you probably have to be more detailed about which threads you are joining. I wouldn’t join the EDT.

Then you need to make sure you are not calling join() in the swing thread. You can do this by creating one thread that is in charge of your download thread. This is essentially just a background worker that you can forget about. It is the worker thread that knows when the download finishes and what to do at that point. You just need to make sure edits to the swing objects are done in the swing thread.

join() doesn’t rethrow exceptions thrown inside the thread. So after join() has released current thread you don’t know whether the thread finished successfully or not.

Читайте также:  Метод trim string java

Источник

Enum Class Thread.State

A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states.

Nested Class Summary

Nested classes/interfaces declared in class java.lang.Enum

Enum Constant Summary

Method Summary

Methods declared in class java.lang.Enum

Methods declared in class java.lang.Object

Enum Constant Details

NEW

RUNNABLE

Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual machine but it may be waiting for other resources from the operating system such as processor.

BLOCKED

Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait .

WAITING

A thread in the waiting state is waiting for another thread to perform a particular action. For example, a thread that has called Object.wait() on an object is waiting for another thread to call Object.notify() or Object.notifyAll() on that object. A thread that has called Thread.join() is waiting for a specified thread to terminate.

TIMED_WAITING

TERMINATED

Method Details

values

valueOf

Returns the enum constant of this class with the specified name. The string must match exactly an identifier used to declare an enum constant in this class. (Extraneous whitespace characters are not permitted.)

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Java thread in wait state

A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states.

Enum Constant Summary

Method Summary

Methods declared in class java.lang.Enum

Methods declared in class java.lang.Object

Enum Constant Detail

NEW

RUNNABLE

Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual machine but it may be waiting for other resources from the operating system such as processor.

BLOCKED

Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait .

WAITING

A thread in the waiting state is waiting for another thread to perform a particular action. For example, a thread that has called Object.wait() on an object is waiting for another thread to call Object.notify() or Object.notifyAll() on that object. A thread that has called Thread.join() is waiting for a specified thread to terminate.

TIMED_WAITING

TERMINATED

Method Detail

values

Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows:

for (Thread.State c : Thread.State.values()) System.out.println(c);

valueOf

Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

Читайте также:  Java learning step by step

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Difference between WAIT and BLOCKED thread states

What is the difference between thread state WAIT and thread state BLOCKED? The Thread.State documentation:

Blocked
A thread that is blocked waiting for a monitor lock is in this state. Waiting
A thread that is waiting indefinitely for another thread to perform a particular action is in this state

@Abdul the geekexplains link says that a thread can go into a blocked state by calling Object.wait() that’s not correct is it?

according to oracle docs docs.oracle.com/javase/6/docs/api/java/lang/…: A thread is in the waiting state due to calling one of the following methods:Object.wait with no timeout, Thread.join with no timeout, LockSupport.park

For the record, I think @Flavio’s answer is a bit better than Ankit’s in case you might consider changing.

6 Answers 6

A thread goes to wait state once it calls wait() on an Object. This is called Waiting State. Once a thread reaches waiting state, it will need to wait till some other thread calls notify() or notifyAll() on the object.

Once this thread is notified, it will not be runnable. It might be that other threads are also notified (using notifyAll() ) or the first thread has not finished his work, so it is still blocked till it gets its chance. This is called Blocked State. A Blocked state will occur whenever a thread tries to acquire lock on object and some other thread is already holding the lock.

Once other threads have left and its this thread chance, it moves to Runnable state after that it is eligible pick up work based on JVM threading mechanism and moves to run state.

You explained it much better because you explained the sequence in which a thread reaches those two states which makes it clearer than just explaining each of the two states in isolation (which is done by «More Than Five»‘s answer

For all those, who wonder why most (all?) of the state diagrams found in the web claim, that notify()/notifyAll() results in RUNNABLE instead of BLOCKED: stackoverflow.com/questions/28378592/…

Assume there is only one thread and waited on some time in millis; now Is it possible a thread can directly from waiting state to go to runnable state? since no other thread takes lock here since only single threaded?

There is a wait(time) method which will get back to runnable state once the time has elapsed. But if no time is specified, it will wait till other thread notifies or the thread is interrupted.

Читайте также:  Java short array to bytes

Your answer is good but it doesn’t quite explain that you can enter a Blocked state anytime you try to acquire a lock. It doesn’t have to have anything to do with signal/notify.

The difference is relatively simple.

In the BLOCKED state, a thread is about to enter a synchronized block, but there is another thread currently running inside a synchronized block on the same object. The first thread must then wait for the second thread to exit its block.

In the WAITING state, a thread is waiting for a signal from another thread. This happens typically by calling Object.wait() , or Thread.join() . The thread will then remain in this state until another thread calls Object.notify() , or dies.

is it correct to say that only a thread itself can make it go into wait? Can Thread-B ever make Thread-A go to WAIT state?

You rarely use Object.wait() directly, but you end up in the WAITING state also using the more high-level concurrency constructs — like locks, blocking queues, etc. broadly speaking, whenever two threads have to coordinate.

Java8 doc for Thread.State says, «. These states are virtual machine states which do not reflect any operating system thread states.» In other words, the JVM does not care about the difference between a thread that is running Java code, a thread that is waiting for a system call to return, or a thread that is waiting for a time slice. Those are all just RUNNABLE as far as the JVM is concerned.

It might be nice to add that when a thread moves from the WAITING state, it must first go to the BLOCKED state until it can acquire the lock associated with the object which it was waiting on.

The important difference between the blocked and wait states is the impact on the scheduler. A thread in a blocked state is contending for a lock; that thread still counts as something the scheduler needs to service, possibly getting factored into the scheduler’s decisions about how much time to give running threads (so that it can give the threads blocking on the lock a chance).

Once a thread is in the wait state the stress it puts on the system is minimized, and the scheduler doesn’t have to worry about it. It goes dormant until it receives a notification. Except for the fact that it keeps an OS thread occupied it is entirely out of play.

This is why using notifyAll is less than ideal, it causes a bunch of threads that were previously happily dormant putting no load on the system to get woken up, where most of them will block until they can acquire the lock, find the condition they are waiting for is not true, and go back to waiting. It would be preferable to notify only those threads that have a chance of making progress.

(Using ReentrantLock instead of intrinsic locks allows you to have multiple conditions for one lock, so that you can make sure the notified thread is one that’s waiting on a particular condition, avoiding the lost-notification bug in the case of a thread getting notified for something it can’t act on.)

Источник

Оцените статью