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");
}
}
}
에 통보 기다립니다. 하지만 도망 가지 마라. synchronized(target)
도 사용하면 우선 순위에 따라 실행되지 않습니다.우리가 자식 스레드에 우선 순위를 부여하고 <code>wait()</code> 및 <code>notifyall()</code> 방법이 그렇게 사용 우선 순위에 따라 실행해야하는 반면 자바
SIR ... 모든 3 개의 스레드가 대기 중입니다 .... 그리고 notifyall 메소드 후 ... 우선 순위가 더 높은 스레드가 먼저 실행될 것인가 아닌가? –
어떤 스레드가 먼저 실행될지는 확실하지 않지만 일반적으로 더 높은 우선 순위의 스레드는 시간상 임의의 순간에 실행되도록 선택 될 가능성이 더 높습니다. – Attila
참, 그는 자신의 잠금 논리를 구현하여 "좋은"실! –