A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

/*
进程间通信;多线程但执行不同语句。

等待唤醒机制:包含wait()、notify()、notifyAll()三种方法,它们均使用在同步中,
                          而且都要对同步中的锁(监视器)进行操作,且同一套方法组合(即等
                          待唤醒)操作同一个锁,因为锁可以是任意对象,所以可以被任意对象
                          调用的方法定义在Object类中。

*/
package thread.communication;

class Resource
{
        private String name;
        private String sex;
        private boolean flag = false;
        public synchronized void setInfo(String name, String sex)
        {
                if(this.flag)
                        try
                        {
                                this.wait();
                        }
                        catch (Exception e)
                        {
                        }
                this.name = name;
                this.sex = sex;
                flag = true;
                this.notify();
        }
        public synchronized void out()
        {
                if(!this.flag)
                        try
                        {
                                this.wait();
                        }
                        catch (Exception e)
                        {
                        }
                System.out.println(name+"-------"+sex);
                flag = false;
                this.notify();
        }
}

class Input implements Runnable
{
        private Resource res;
        Input(Resource res)
        {
                this.res = res;
        }
        public void run()
        {
                int x = 0;
                while(true)
                {
                        if(x==0)
                                res.setInfo("Ryan","male");
                        else
                                res.setInfo("李娜","女");
                        x=(x+1)%2;
                }
        }
}

class Output implements Runnable
{
        private Resource res;
        Output(Resource res)
        {
                this.res = res;
        }
        public void run()
        {
                while(true)
                {
                        res.out();
                }
        }
}

class CommunicationThread
{
        public static void main(String[] args)
        {
                Resource res = new Resource();
                new Thread(new Input(res)).start();
                new Thread(new Output(res)).start();
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马