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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 442851994 中级黑马   /  2012-11-10 14:21  /  1239 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 442851994 于 2012-11-14 21:53 编辑

为什么我在wait方法中加入时间后会连着出现两个生产,然后连着出现两个消费呢??下面是源代码:
public class Thread7 {
        public static void main(String[] args) {
                        Resourse r=new Resourse();
                        dust d=new dust(r);
                        consumer s=new consumer(r);
                        new Thread(d).start();
                        new Thread(s).start();
        }
}
//资源
class Resourse{
        private String name;
        boolean flag;
        private int count;
        public synchronized void set(String name){
                this.name=name+count;
                if(flag)
                        try {
                                this.wait(100000);
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                System.out.println(Thread.currentThread().getName()+"........生产者......"+this.name);
                count++;
                flag=true;
                this.notify();
        }
        public synchronized void get(){
                if(!flag)
                        try {
                                this.wait(100000);
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName()+".....消费者...."+this.name);
                        flag=false;
                        this.notify();
        }
}
//生产者
class dust implements Runnable{
        private Resourse r;
        dust(Resourse r){
                this.r=r;
        }
                public void run(){
                        while(true){
                        r.set("馒头");
                }
        }
}
//消费者
class consumer implements Runnable{
        private Resourse r;
        consumer(Resourse r){
                this.r=r;
        }
        public void run() {
                while(true){
                        r.get();
                }
        }
        
}

点评

加入时间后,等待到指定时间就会自动启动,而你又使用this.notify唤醒了当前线程,就会又执行一次,this代表当前对象的  发表于 2012-11-10 14:31

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 赞一个!

查看全部评分

1 个回复

倒序浏览

  void wait()
           导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。
  void wait(long timeout)
           导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过指定的时间量。
  void wait(long timeout, int nanos)
           导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者其他某个线程中断当前线程,或者已超过某个实际时间量。

在没添加时间条件时,线程必须等其他线程notify()或notifyAll()本线程才会被唤醒,否则继续等,加入时间后
该生产的线程就有了最大等待时间timeout,时间到wait就返回。这时候该线程如果这个时候获得了对象的锁,那么可以向下执行,即执行生产
该若生产线程在没等到最大等待时间timeout,消费线程已经退出并释放了锁,调用notify唤醒了生产线程,这时候也被唤醒了可以往下执行,进行生产

消费线程同理

点评

应该给结合代码说下,会更清晰点吧  发表于 2012-11-10 15:45

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 赞一个!

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马