当前位置: 代码迷 >> J2SE >> 实现线程一个游戏功能,该如何处理
  详细解决方案

实现线程一个游戏功能,该如何处理

热度:143   发布时间:2016-04-24 02:32:05.0
实现线程一个游戏功能
要求: 实现两个线程 一个线程打印“乒”一个线程打印“乓” 它们之间是互相叫醒对方。

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

------解决方案--------------------
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);                    }                }            }        }    }}
  相关解决方案