public class PrintOddEven {
private static int count = 0;
private static final Object lock = new Object();
static class TurningRunner implements Runnable {
@Override
public void run() {
while (count <= 100) {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + ":" + count++);
lock.notify();
if (count <= 100) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args) throws InterruptedException {
new Thread(new TurningRunner(), "偶数线程").start();
Thread.sleep(100);
new Thread(new TurningRunner(), "奇数线程").start();
}
}
两个线程交替打印奇、偶数
最新推荐文章于 2021-11-17 16:59:19 发布