收藏 (0) +1 (0) +1 (0) +1
收藏成功查看收藏>>

正在阅读:攻克学习多线程时碰到的难题攻克学习多线程时碰到的难题

2004-03-26 10:05 出处:PConline 作者:qlampskyface 责任编辑:linjixiong

      catch (InterruptedException e) {
        //keep trying
      }
    }
    count++;
    notifyAll(); //alert a thread that's blocking on this semaphore
  }

  public void run() {
    while (true) {
      if (Thread.currentThread().getName().substring(0,8).equalsIgnoreCase("consumer")) {
        acquire();
      }
      else if (Thread.currentThread().getName().substring(0,8).equalsIgnoreCase("producer")) {
        release();
      }
      System.out.println(Thread.currentThread().getName() + " " + count);
    }
    }
  }
       生产者生产,消费者消费,一般没有冲突,但当库存为0时,消费者要消费是不行的,但当库存为上限(这里是10)时,生产者也不能生产.请好好研读上面的程序,你一定会比以前进步很多.

      上面的代码说明了synchronized和wait,notify没有绝对的关系,在synchronized声明的方法、代码块中,你完全可以不用wait,notify等方法,但是,如果当线程对某一资源存在某种争用的情况下,你必须适时得将线程放入等待或者唤醒.

文章终于写完了,基本上将我学习所得全部写出来了,不过也留下些许遗憾,比如synchronized后是类时的深入的说明及讨论.而且,文章由于自己能力有限,有些地方肯定会有错误,希望看过有何建议和批评,请发帖在下面,我会修正该文.谢谢!


 

察看评论详细内容 我要发表评论
作者笔名简短内容 发表时间
:
键盘也能翻页,试试“← →”键

相关文章

关注我们

最新资讯离线随时看 聊天吐槽赢奖品
手机访问回到顶部