class EvenOddPrinter { public static void main(String[] args) throws Exception { R r = new R(); new Thread("偶数线程") { @Override public void run() { while (r.v < 100) { try { r.printOdd(); } catch (Exception e) { e.printStackTrace(); } } } }.start(); new Thread("奇数线程") { @Override public void run() { while (r.v < 100) { try { r.printEven(); } catch (Exception e) { e.printStackTrace(); } } } }.start(); } static class R { private int v = 0; private Object lock = new Object(); synchronized void printEven() throws Exception { if (v % 2 != 0) { System.out.println(Thread.currentThread().getName() + ":" + v++); notifyAll(); wait(); } } synchronized void printOdd() throws Exception { if (v % 2 == 0) { System.out.println(Thread.currentThread().getName() + ":" + v++); notifyAll(); wait(); } } }}