Java Reference
In-Depth Information
integer array. This object is called sa and because it is static , there is only one copy of it
that is shared by all instances of MyThread . Finally, the class Sync creates two threads
and has each compute the sum of an integer array.
Inside sumArray( ) , sleep( ) is called to purposely allow a task switch to occur, if one
can—but it can't. Because sumArray( ) is synchronized, it can be used by only one thread
at a time. Thus, when the second child thread begins execution, it does not enter sumAr-
ray( ) until after the first child thread is done with it. This ensures that the correct result is
produced.
To fully understand the effects of synchronized , try removing it from the declaration of
sumArray( ) . After doing this, sumArray( ) is no longer synchronized, and any number
of threads may use it concurrently. The problem with this is that the running total is stored
in sum , which will be changed by each thread that calls sumArray( ) through the static
object sa . Thus, when two threads call sa.sumArray( ) at the same time, incorrect results
are produced because sum reflects the summation of both threads, mixed together. For ex-
ample, here is sample output from the program after synchronized has been removed from
sumArray( ) 's declaration. (The precise output may differ on your computer.)
As the output shows, both child threads are calling sa.sumArray( ) concurrently, and the
value of sum is corrupted. Before moving on, let's review the key points of a synchronized
method:
Search WWH ::




Custom Search