Tuesday, August 17, 2010

Multithreading: Traffic2.java

Courtesy of Sun Web Learning Center



 3. public class Traffic2 implements Runnable {
 4.   static String s = "";
 5.   static final int HOW_BUSY = 100;
 6.   public void run() {
 7.     for(int j = 0; j < HOW_BUSY * 9; j++)
 8.       if((j % HOW_BUSY) == 0) s += "2";
 9.   }
10.   public static void main(String[] args) {
11.     Thread t = new Thread(new Traffic2());  t.start();
12.     for(int k = 0; k < HOW_BUSY * 9; k++)  if((k % HOW_BUSY) == 0) s += "1";
13.     try { t.join(); } catch (Exception e) { }
14.     System.out.println(s);
15. } }

If the value of HOW_BUSY is changed from 100 to 100000000, what is the most likely result?


A Compilation fails.
B An exception is thrown at runtime.
C There would be no impact to the output.
D The total number of characters output might change.
E "1" characters would be more evenly distributed throughout the output.
F "1" characters would be clumped near the beginning or end of the output.


E is correct. As the code stands, there isn't much work for the two threads to do, so it's most likely that one thread will do all of it's work and then let the other thread execute. If HOW_BUSY is changed to 10 million, each thread will have a lot of work to do, and it's more likely that the threads will take turns.

No comments:

Post a Comment