日期:2014-05-20 浏览次数:20625 次
public class Test { public static void main(String[] args) throws Throwable { Object locker = new Object(); new TestThread("乒", locker).start(); new TestThread("乓", locker).start(); } static class TestThread extends Thread { static boolean flag = true; Object locker; publit TestThread(String name, Object locker) { super(name); this.locker = locker; } public void run() { while (true) { synchronized(locker) { try { if (getName().equals("乒")) { if (!flag) { locker.wait(); } } else { if (flag) { locker.wait(); } } flag = !flag; System.out.print(getName()); locker.notifyAll(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } } } } }