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
SIR ...因爲所有3個線程都在等待...並且在notifyall方法之後......具有更多優先級的線程將首先運行或不運行? –
不知道哪個線程會先運行,但一般來說,更高優先級的線程有更高的機會在任何時刻被選中執行 – Attila
是的,儘管他可以實現自己的鎖定邏輯以便能夠通知「好」線程! –