wait()とnotify()は静的ではないため、コンパイラーは、待機を静的コンテキストから呼び出す必要があるというエラーを出す必要があります。
public class Rolls {
public static void main(String args[]) {
synchronized(args) {
try {
wait();
} catch(InterruptedException e)
{ System.out.println(e); }
}
}
}
ただし、次のコードは正しくコンパイルおよび実行されます。コンパイラがここでエラーを出さないのはなぜですか?あるいは、コンパイラが前のコードで、静的コンテキストから呼び出す必要があるというエラーを出すのはなぜですか?
public class World implements Runnable {
public synchronized void run() {
if(Thread.currentThread().getName().equals("F")) {
try {
System.out.println("waiting");
wait();
System.out.println("done");
} catch(InterruptedException e)
{ System.out.println(e); }
}
else {
System.out.println("other");
notify();
System.out.println("notified");
}
}
public static void main(String []args){
System.out.println("Hello World");
World w = new World();
Thread t1 = new Thread(w, "F");
Thread t2 = new Thread(w);
t1.start();
t2.start();
}
}