要求: 实现两个线程   一个线程打印“乒”一个线程打印“乓”  它们之间是互相叫醒对方。   打印结果为:  乒乓   乒乓  乒乓   乒乓
  
  注(别拿生产者与消费者例子出来)。

解决方案 »

  1.   

    for example
    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);
                        }
                    }
                }
            }
        }
    }
      

  2.   

    我自己来实现代码:public class PingPangGame extends Thread
    {
        Object locker;
        
        public PingPangGame(String name, Object locker)
        {
            super(name);
            this.locker = locker;
        }
        
        public void run()
        {
            while (true)
            {
                synchronized (locker)
                {
                    try
                    {
                        locker.notifyAll();
                        locker.wait();
                        System.err.print(getName());
                        
                        locker.wait(1000);
                        
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                        System.exit(-1);
                    }
                }
            }
        }
        
        public static void main(String[] args) throws Throwable
        {
            Object locker = new Object();
            new PingPangGame("乒", locker).start();
            new PingPangGame("乓", locker).start();
        }
    }