Friday, August 27, 2010

Multithreading: Traffic.java

Courtesy of Sun Web Learning Center

Given:

3. public class Traffic implements Runnable {
4.     static String s = "";
5.     public void run() {
6.        for(int j = 0; j < 90000000; j++) {
7.          if((j % 10000000) == 0) Thread.yield(); // optional?
8.          if((j % 10000000) == 0) s += "2";
9. } }
10. public static void main(String[] args) {
11.    Thread t = new Thread(new Traffic()); t.start();
12.    for(int k = 0; k < 90000000; k++) if((k%10000000) == 0) s += "1";
13.    try { t.join(); } catch (Exception e) { }
14.    System.out.println(s);
15. } }
What would be the most likely impact to the output if line 7 was removed?


A There would be no impact to the output.
B Compilation would fail if line 7 was removed.
C An exception would be thrown if line 7 was removed.
D The total number of characters output might change.
E The character "2" would appear more frequently near the end of the output.
F The character "2" would appear less frequently near the end of the output.


F is correct. As the code stands the yield() will tend to give priority to the main thread, which will tend to place more "2" characters near the end of the output.

No comments:

Post a Comment