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
是的,尽管他可以实现自己的锁定逻辑以便能够通知“好”线程! –