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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 奋上 中级黑马   /  2014-7-31 23:16  /  1453 人查看  /  8 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

/*
生产者,消费者的例子
必须写while循环、notifyAll
*/



class Res
{
        private String name;
        private int count = 1;
        private boolean flag = false;

        public synchronized void set(String name)
        {
                while (flag)
                {
                        try{wait();}catch(Exception e){}
                        this.name = name+count++;
                        System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
                        flag = true;
                        this.notifyAll();
                }
        }

        public synchronized void show()
        {
                while (!flag)
                {
                        try{wait();}catch(Exception e){}
                        System.out.println(Thread.currentThread().getName()+"...消费者.........."+this.name);
                        flag = false;
                        this.notifyAll();
                }
        }
}


class Pro implements Runnable
{
        private Res r;
        Pro(Res r)
        {
                this.r = r;
        }

        public void run()
        {
                while (true)
                {
                        r.set("商品");
                }
        }
}


class Con implements Runnable
{
        private Res r;
        Con(Res r)
        {
                this.r = r;
        }

        public void run()
        {
                while (true)
                {
                        r.show();
                }
        }
}


class  ProConDemo
{
        public static void main(String[] args)
        {
                Res r = new Res();

                Pro p = new Pro(r);
                Con c = new Con(r);

                Thread t1 = new Thread(p);
                Thread t2 = new Thread(p);
                Thread t3 = new Thread(c);
                Thread t4 = new Thread(c);

                t1.start();
                t2.start();
                t3.start();
                t4.start();
        }
}







QQ截图20140731231544.jpg (39.7 KB, 下载次数: 11)

QQ截图20140731231544.jpg

8 个回复

倒序浏览
求大神给看看
回复 使用道具 举报
没人吗?
回复 使用道具 举报
据我猜测,还会发出几声嗡鸣声……
回复 使用道具 举报
是不是默认编码方式换了
回复 使用道具 举报
太长了,看的好晕
回复 使用道具 举报
wisely 发表于 2014-8-1 20:35
据我猜测,还会发出几声嗡鸣声……

对的,对的,还发出了几声声音,编译出来少个Con类文件,是怎么回事呢?
回复 使用道具 举报
奋上 发表于 2014-8-1 20:50
对的,对的,还发出了几声声音,编译出来少个Con类文件,是怎么回事呢? ...

{:3_55:}
我忘了……
回复 使用道具 举报
hmid 来自手机 中级黑马 2014-8-2 00:36:13
9#
确认源文件的编码方式。编译时使用javac -encoding utf-8
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马