在java中等待通知

时间:2012-05-17 09:48:39

标签: java multithreading thread-priority

class Callme {
    void call(String msg) {
        System.out.print("[" + msg);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted");
        }
        System.out.println("]");    
    }
}    

class Caller implements Runnable {
    String msg;
    Callme target;
    Thread t;
    public Caller(Callme targ, String s) {
        target = targ;
        msg = s;
        t = new Thread(this);
        t.start();
    }

    public void run() {
        //synchronized(target){ // synchronized block
        target.call(msg);
        //}
    }
}
class Synch {
    public static void main(String args[]) {
        Callme target = new Callme();
        Caller ob1 = new Caller(target, "Hello");
        ob1.t.setPriority(Thread.NORM_PRIORITY);
        Caller ob2 = new Caller(target, "Synchronized");
        Caller ob3 = new Caller(target, "World");
        ob2.t.setPriority(Thread.MAX_PRIORITY);
        ob3.t.setPriority(Thread.MIN_PRIORITY);
        System.out.println(ob1.t.getPriority());
        System.out.println(ob2.t.getPriority());
        System.out.println(ob3.t.getPriority());
        // wait for threads to end
        try {
            ob1.t.wait();
            ob2.t.wait();
            ob3.t.wait();
            ob1.t.notifyAll();

        } catch(InterruptedException e) {
            System.out.println("Interrupted");
        }
    }
}

我们优先考虑子线程,并使用wait()notifyall()方法,因此必须按优先级运行。但不要跑。如果我们也使用synchronized(target),那么也不会按优先级运行。

3 个答案:

答案 0 :(得分:2)

Tread.setPriority()更改了线程的执行优先级,这意味着更高优先级的线程在运行时更有可能被选中执行(与同时运行的低优先级线程相比)。当然,如果你通过对wait()的激活调用来停止线程,它将在等待时不会运行,因此在这种情况下优先级毫无意义。

更新:如上所述,优先级是运行线程。当您调用notify()时,所选线程不是基于优先级(至少不保证,规范不会说明这种或那种)

答案 1 :(得分:1)

这取决于程序运行的操作系统。很少有操作系统不关注应用程序设置的优先级 - 或者出乎意料地行为。因此,不应该依赖优先权。

找到了类似的帖子:

Thread priority and Thread accuracy

答案 2 :(得分:1)

Java Language Specification, 17.2.2 Notification:

“无法保证等待集中的哪个线程被选中。”

记下精心挑选的术语:等待设置