日期:2014-05-20  浏览次数:20577 次

实现线程一个游戏功能
要求: 实现两个线程 一个线程打印“乒”一个线程打印“乓” 它们之间是互相叫醒对方。

  打印结果为: 乒乓 乒乓 乒乓 乒乓
  
  注(别拿生产者与消费者例子出来)。

------解决方案--------------------
for example
Java code
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);
                    }
                }
            }
        }
    }
}