分享一下,自己实现的两个线程交替打印的代码,核心思想是使用synchronized对象锁+wait(),notifyAll()方法。
public class OddEvenPrinter implements Runnable {
private final int times;
private volatile int count;
private final Object Lock = new Object();
public OddEvenPrinter(int times,int count){
this.times = times;
this.count = count;
}
@Override
public void run(){
while (count<times) {
synchronized (Lock) {
System.out.println(Thread.currentThread().getName() + "打印数字:" + (++count));
Lock.notifyAll();
try {
Lock.wait();
} catch (Exception e) {
};
}
}
}
public static void main(String[] args){
OddEvenPrinter printer = new OddEvenPrinter(10,0);
new Thread(printer,"thread-1").start();
new Thread(printer,"thread-2").start();
}
}
创建了两个线程对象,一个锁对象,一个实现了Runnable接口的类。
调用wait()方法会释放锁,调用notifyAll()不会释放当前线程持有的锁。