交替打印
使用wait(),notify(),notifyAll()
public class 交替打印 {
/**
* 两个线程交替打印1-100
* @param args
*/
public static void main(String[] args) {
/*PrintNumber1 printNumber = new PrintNumber1();*/
PrintNumber2 printNumber = new PrintNumber2();
Thread t1 = new Thread(printNumber,"线程1");
Thread t2 = new Thread(printNumber,"线程2");
t1.start();
t2.start();
}
/**
* 使用类锁
*/
static class PrintNumber1 implements Runnable{
int i = 0;
@Override
public void run() {
while (true){
synchronized (this){
notify();
if(i<100){
i++;
System.out.println(Thread.currentThread().getName()+"--打印:"+i);
}else {
break;
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
/**
* 使用对象锁
*/
static class PrintNumber2 implements Runnable{
int i =0;
private Object object = new Object();
@Override
public void run() {
while (true){
synchronized (object){
object.notify();
if(i<100){
i++;
System.out.println(Thread.currentThread().getName()+"--打印:"+i);
}else {
break;
}
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
注意wait(),notify(),notifyAll()三个方法的调用者必须是同步代码块或者同步方法中的同步监视器(锁),在上面的例子,同步代码块的锁为object对象,而现在notify和wait方法的调用者是this,即Number对象的实例,我们需要改成object去调用notify()和wait()方法即可。