Java Reference
In-Depth Information
yield()
,or
Running
time out
run()
completed
start()
Thread created
run()
New
Ready
Finished
join()
sleep()
wait()
Target
finished
Wait for target
to finish
Wait for time
out
Wait to be
notified
Time out
Signaled
Blocked
F IGURE 30.25
A thread can be in one of five states: New, Ready, Running, Blocked, or Finished.
A thread can enter the Blocked state (i.e., become inactive) for several reasons. It may have
invoked the join() , sleep() , or wait() method. It may be waiting for an I/O operation
to finish. A blocked thread may be reactivated when the action inactivating it is reversed. For
example, if a thread has been put to sleep and the sleep time has expired, the thread is reacti-
vated and enters the Ready state.
Finally, a thread is Finished if it completes the execution of its run() method.
The isAlive() method is used to find out the state of a thread. It returns true if a thread
is in the Ready , Blocked , or Running state; it returns false if a thread is new and has not
started or if it is finished.
The interrupt() method interrupts a thread in the following way: If a thread is currently
in the Ready or Running state, its interrupted flag is set; if a thread is currently blocked, it is
awakened and enters the Ready state, and a java.lang.InterruptedException is thrown.
30.34
What is a thread state? Describe the states for a thread.
Check
Point
30.15 Synchronized Collections
Java Collections Framework provides synchronized collections for lists, sets, and maps.
Key
Point
The classes in the Java Collections Framework are not thread-safe; that is, their contents may
become corrupted if they are accessed and updated concurrently by multiple threads. You can
protect the data in a collection by locking the collection or by using synchronized collections.
The Collections class provides six static methods for wrapping a collection into a syn-
chronized version, as shown in Figure 30.26. The collections created using these methods are
called synchronization wrappers .
synchronized collection
synchronization wrapper
java.util.Collections
+synchronizedCollection(c: Collection): Collection
+synchronizedList(list: List): List
+synchronizedMap(m: Map): Map
+synchronizedSet(s: Set): Set
+synchronizedSortedMap(s: SortedMap): SortedMap
Returns a synchronized collection.
Returns a synchronized list from the specified list.
Returns a synchronized map from the specified map.
Returns a synchronized set from the specified set.
Returns a synchronized sorted map from the specified
sorted map.
Returns a synchronized sorted set.
+synchronizedSortedSet(s: SortedSet): SortedSet
F IGURE 30.26
You can obtain synchronized collections using the methods in the Collections class.
 
 
 
Search WWH ::




Custom Search