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)
也使用,那么也不按优先级运行。