Comment out the word “synchronized” in the heading of the method update. Compile and run RunThread3 again. What is the outcome? Explain.

Consider the following Java classes:
```
import SomeThread3;
public class RunThreads3
{
public static void main (String[] args)
{
int originalThreadCount = Thread.activeCount( );
for (int i=0; i<10; i++) {
Thread p = new Thread(new SomeThread3());
p.start();
System.out.println("thread count=" +Thread.activeCount( ));
}

while (Thread.activeCount() > originalThreadCount ){
// loop until all child threads have exited.
}
System.out.println("finally, Count = " + SomeThread3.count);
}
}//end class RunThreads3

class SomeThread3 implements Runnable {
static int count=0;

SomeThread3() {
super();
}

public void run() {
update();
}

static public synchronized void update( ){
int myCount = count;

int second = (int)(Math.random( ) * 500);
try {
Thread.sleep(second);
}
catch (InterruptedException e) {
}

myCount++;
count = myCount;
System.out.println("count="+count+
"; thread count=" + Thread.activeCount( ));
}
} //end class SomeThread3
```


Now the method is no longer thread safe. Now the ten threads can execute the method concurrently, each incrementing the value of the version of the static count that it retrieved from. Due to the interleaved execution of the threads, some of the incrementing can be expected to overlap each others, resulting in a final count of an integer value in the range of 1 to 10.

Here is a sample run outcome:
thread count=3
thread count=4
thread count=5
thread count=6
thread count=7
thread count=8
thread count=9
thread count=10
thread count=11
thread count=12
count=1; thread count=12
count=1; thread count=11
count=2; thread count=10
count=1; thread count=9
count=1; thread count=8
count=1; thread count=7
count=2; thread count=6
count=1; thread count=5
count=1; thread count=4
count=1; thread count=3
finally, Count = 1
Note that at two points the static count was 2 – two of the threads started with a value of 1.

Computer Science & Information Technology

You might also like to view...

The number of degrees that an arc traverses from its starting angle is known as the _____________.

a) traversed angle b) size c) arc angle d) None of the above.

Computer Science & Information Technology

Which of the following is an example of a third-party payment processor?

A. Yahoo! Small Business B. Microsoft Office Live Small Business C. Network Solutions D. none of the above

Computer Science & Information Technology

A common problem with column-based CSS layouts is that a column is really just a(n) ____, and is therefore only as tall as the content it contains.

A. attribute B. id C. div D. tag

Computer Science & Information Technology

To make a specific database active, you must execute the ____ database statement.

A. CHANGE B. USE C. SWITCH D. SELECT

Computer Science & Information Technology