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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 sepallen 于 2015-4-10 18:18 编辑

跟着毕老师视频练习代码发现程序执行不动了,不应该发生死锁吧?
代码如下:

package com.javastudy.cn;

public class Lesson25 {

        /**
         * @param args
         */
        public static void main(String[] args) {
               
                Reource r = new Reource();
               
                Producer pro = new Producer(r);
                Consumer con = new Consumer(r);
               
                Thread t1 = new Thread(pro);
                Thread t2 = new Thread(con);
                t1.start();
                t2.start();
        }
}
class Reource{
        private String name;
        private int count =1;
        private boolean flag = false;

        public synchronized void set(String name){
                if(flag)
                        try{wait();}catch(Exception e){}
                this.name = name+"--"+count++;
                System.out.println(Thread.currentThread().getName()+"生产"+this.name);
                flag = true;
                notify();
        }
        public synchronized void out(){
                if(!flag)
                        try{wait();}catch(Exception e){}
                System.out.println(Thread.currentThread().getName()+"消费。。。。"+this.name);
                flag = false;
                notify();
        }
}
class Producer implements Runnable{
        private Reource res;
        Producer(Reource res){
                this.res = res;
        }
        public void run(){
                while(true){
                        res.set("+商品+");
                }
        }
}
class Consumer implements Runnable{
        private Reource res;
        Consumer(Reource res){
                this.res = res;
        }
        public void run(){
                res.out();
        }
}

7 个回复

倒序浏览
可能是几个线程都挂住了,醒不了
回复 使用道具 举报
殷俊 发表于 2015-4-10 17:27
可能是几个线程都挂住了,醒不了

不应该吧 一共只有两个线程 只能是一个唤醒另一个 不存在都挂起的情况吧?
回复 使用道具 举报
你多搞几个线程肯定挂啊!!!
回复 使用道具 举报
sepallen 发表于 2015-4-10 17:35
不应该吧 一共只有两个线程 只能是一个唤醒另一个 不存在都挂起的情况吧? ...

额,看出问题了,你消费为什么没有while循环?不然的话,只消费一张票就完了,然后就醒不了了

评分

参与人数 1黑马币 +2 收起 理由
sepallen + 2 赞一个!

查看全部评分

回复 使用道具 举报 1 0
zouxx 发表于 2015-4-10 17:39
你多搞几个线程肯定挂啊!!!

现在就已经挂了 本不应该挂的
回复 使用道具 举报
殷俊 发表于 2015-4-10 18:03
额,看出问题了,你消费为什么没有while循环?不然的话,只消费一张票就完了,然后就醒不了了 ...

给力啊 谢了哥们
回复 使用道具 举报
殷俊 高级黑马 2015-4-10 18:17:03
8#
:handshake多多交流,共同进步
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马