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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

public class Demo{
        public static void main(String[] args){
                Resource r = new Resource();
                Producer p = new Producer(r);
                Consumer c = new Consumer(r);
                Thread t1 = new Thread(p);
                Thread t2 = new Thread(c);
                t1.start();
                t2.start();
        }
}
class Resource {
        String name;
        int count = 1;
        boolean flag = true;
        public void set(String name){
                while(true){
                        if(flag){
                                synchronized(this){
                                        this.name = name+count++;
                                        System.out.println(Thread.currentThread().getName()+this.name+"....."+"生产");
                                        flag = false;
                                }
                        }
                }
        }
        public void out(){
                while(true){
                        if(!flag){
                                synchronized(this){
                                        System.out.println(Thread.currentThread().getName()+name+"..."+"消费");
                                        flag = true;
                                }
                        }
                }
        }
}
class Producer implements Runnable{
        private Resource r;
        Producer(Resource r){
                this.r = r;
        }
        public void run(){
                r.set("商品");
        }
}
class Consumer implements Runnable{
        private Resource r;
        Consumer(Resource r){
                this.r = r;
        }
        public void run(){
                r.out();
        }
}

9 个回复

倒序浏览
新手不是很懂
回复 使用道具 举报
首先,r是共享资源,,r中的成员变量,flag,name,count都在run方法用到,有多条语句操作它们,所以应该吧它们放在属于同一个锁的代码块中,
回复 使用道具 举报
高昌德 发表于 2015-5-6 13:50
首先,r是共享资源,,r中的成员变量,flag,name,count都在run方法用到,有多条语句操作它们,所以应该吧它 ...

还没有写完就一部小心提交了,,,
首先flag是true,set方法先执行了一遍,把flag置为了false,循环回来判断flag为false,
接着out方法执行一遍,把flag置为了true,当set方法的if判断为true时,进到if里面但没有拿到锁,就停在那了,然后out方法判断为flag为true,也没法进入if里面,也等在那了,,,,,
你把synchronized放到if的上边就可以了,,,,,
回复 使用道具 举报
晕倒,逻辑错误了,兄弟!你得目的是要让生产者和消费者都能够跑起来,那样的就话就要让set方法和out方法都多次运行呀,
所以while(true){}的语句应该写在run方法中呀,你想想是不是嘛?
所以:上面的Resource类中不能用while循环哈,
重点是:

2015年5月6日15时12分11秒.jpg (982 KB, 下载次数: 3)

while(true)用在这里才是正确的

while(true)用在这里才是正确的
回复 使用道具 举报
我是来学习的
回复 使用道具 举报
应该是锁的问题。
回复 使用道具 举报
高昌德 发表于 2015-5-6 14:03
还没有写完就一部小心提交了,,,
首先flag是true,set方法先执行了一遍,把flag置为了false,循环回来 ...

谢谢    明白了     
回复 使用道具 举报
wkz_crystal 发表于 2015-5-6 15:13
晕倒,逻辑错误了,兄弟!你得目的是要让生产者和消费者都能够跑起来,那样的就话就要让set方法和out方法都 ...

谢了   兄弟      其实我纠结的是程序为什么停掉。    你的思考方法很值得学习
回复 使用道具 举报
新手表示不是很理解~~~帮不上你~~
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马