黑马程序员技术交流社区

标题: 如何用单例解决这个程序!急求高手!!! [打印本页]

作者: Spring up    时间: 2012-12-17 09:40
标题: 如何用单例解决这个程序!急求高手!!!
class Res
{
        private String name;
        private String sex;
        private boolean flag=false;
       
        public synchronized void set(String name,String sex)
        {
                if(flag)
                                try{this.wait();}catch(Exception e){}
                        this.name=name;
                        this.sex=sex;               
                        flag=true;
                        this.notify();
        }
       
        public synchronized void out()
        {
                if(!flag)
                        try{this.wait();}catch(Exception e){}
                System.out.println(name+"......"+sex);
               
                flag=false;
                this.notify();
        }
}

class Input implements Runnable
{
        private Res r;
        Input(Res r)
        {
                this.r=r;
        }
       
        public void run()
        {
                boolean b=true;
                while(true)
                {
                        if(b)
                        {
                                r.set("zhangsan", "man");
                                b=false;
                        }
                        else
                        {
                                r.set("张三", "男");
                                b=true;
                        }
                }
        }
}

class Outer implements Runnable
{
        private Res r;
        Outer(Res r)
        {
                this.r=r;
        }
       
        public void run()
        {
                while(true)
                {
                r.out();
                }
        }
}
public class InputOutputDemo {

        /**
         * @param args
         */
        public static void main(String[] args) {
                // TODO Auto-generated method stub

                Res r=new Res();
               
                Input in=new Input(r);
                Outer out=new Outer(r);
               
                Thread t1=new Thread(in);
                Thread t2=new Thread(out);
               
                t1.start();
                t2.start();
        }

}
这个程序用单例 该怎么做?求高手!谢谢!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2