public class Test {
public static void main(String... args) {
Object lock = new Object();
Thread a = new Thread(new MyRunnable(lock, "A"));
Thread b = new Thread(new MyRunnable(lock, "B"));
a.start();
b.start();
}
}
class MyRunnable implements Runnable {
private Object lock;
private String msg;
public MyRunnable(Object lock, String msg) {
this.lock = lock;
this.msg = msg;
}
public void run() {
while (true) {
synchronized (lock) {
System.out.println(msg);
lock.notify();
try {
Thread.sleep(500);
lock.wait();
} catch (InterruptedException exc) {
// ignore
}
}
}
}
}