2012-05-17 55 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

是的,儘管他可以實現自己的鎖定邏輯以便能夠通知「好」線程! –