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)
,那么也不会根据优先级运行。
最佳答案
Tread.setPriority()
更改线程的执行优先级,这意味着更高优先级的线程在运行时更有可能被选中执行(与并发运行的较低优先级相比线)。当然,如果你通过显式调用 wait()
来停止线程,它在等待时不会运行,所以在这种情况下优先级是没有意义的。
更新:如上所述,优先级用于运行 线程。当您调用 notify()
时,所选择的线程不是基于优先级的(至少不能保证如此,规范没有说明这种或那种方式)
关于java - 在 Java 中等待通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10633326/