public class OutputThread implements Runnable {
private int num;
private Object lock;
public OutputThread(int num, Object lock){
super();
this.num = num;
this.lock = lock;
}
public void run(){
while(true){
synchronized (lock) {
lock.notifyAll();
try {
lock.wait();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(num);
}
}
}
public static void main(String[] args) {
Object lock = new Object();
Thread t1 = new Thread(new OutputThread(1,lock));
Thread t2 = new Thread(new OutputThread(2,lock));
t1.start();
t2.start();
}
}
上面代码实现的是通过wait()和notify()实现1 2 1 2...的输出结果,需要注意的是使用wait()方法前,需要获得对象锁,其次wait()方法需要在一个循环中使用,指明跳出循环的条件,在wait()方法执行时,当前线程会释放obj的独占锁,工其他线程使用,当在等待的线程收到notify时间,从新获得独占锁,继续运行,方法notify唤醒一个等待在当前对象上的线程,如果当前有多个线程等待,那么notify随机唤醒一个,如果使用notifyAll唤醒全部等待。