2012-05-17 111 views
1
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),那么也不按优先级运行。等待通知在java

回答

1

它取决于程序运行的操作系统。很少有操作系统不理会应用程序设置的优先级 - 或意外行为。因此,不应该依赖于优先事项。

类似线程发现:

Thread priority and Thread accuracy

2

Tread.setPriority()改变线程,这意味着更高的优先级线程的运行时,越来越挑执行一个更好的机会的执行优先级(相对于同时运行的较低优先级的线程)。当然,如果您通过对wait()的明确呼叫停止线程,它在等待时不会运行,所以在这种情况下优先级没有意义。

更新:优先如上所述为运行线程。当你调用notify()选择的线程不是基于优先级(至少它不能保证,该规范并没有说这种或那种方式)

+0

SIR ...因为所有3个线程都在等待...并且在notifyall方法之后......具有更多优先级的线程将首先运行或不运行? –

+0

不知道哪个线程会先运行,但一般来说,更高优先级的线程有更高的机会在任何时刻被选中执行 – Attila

+0

是的,尽管他可以实现自己的锁定逻辑以便能够通知“好”线程! –