<< ECMAScript Harmony | Home | Friday Java Final Exam: Class Loaders >>

Friday Java Quiz: Thread Priorities

The standard advice given about using Java thread priorities can be found on p.218 in Java Concurrency In Practice:

Avoid the temptation to use thread priorities, since they increase platform dependence and can cause liveness problems. Most concurrent applications can use the default priority for all threads.

But when was the last time good advice prevented us from having a little fun?

Q: What will the following Java program print?

public class Foo {
  public static void main(String[] args) throws Exception {
    MyThread[] ts = new MyThread[] {new MyThread(), new MyThread()};
    ts[0].setPriority(Thread.MAX_PRIORITY);
    ts[1].setPriority(Thread.MIN_PRIORITY);
    for (Thread t: ts) t.start();
    Thread.sleep(1000);
    synchronized(MyThread.class) {
      MyThread.done = true;
    }
    for (Thread t: ts) t.join();
    System.out.println(ts[0].counter > ts[1].counter);
  }
}

class MyThread extends Thread {
  public static boolean done = false;
  public int counter = 0;
  public void run() {
    while (true) synchronized(MyThread.class) {
      if (done) return;
      counter++;
    }
  }
}
Tags :


Re: Friday Java Quiz: Thread Priorities

1. The program does not read counter correctly. So the output could be either true or false. 2. On a two+ core m/c the ouput again is not determinable

Re: Friday Java Quiz: Thread Priorities

take my earlier comment back. Did not see the join.

Re: Friday Java Quiz: Thread Priorities

Well, I'd say true. But I'm sure it doesn't, otherwise you wouldn't have asked, I guess?

Add a comment Send a TrackBack