正在阅读:Java基本教学:线程入门Java基本教学:线程入门

2004-08-13 10:30 出处:太平洋电脑网 作者:mingjava 责任编辑:linjixiong


  public class CubbyHole {
  private int contents;
  private boolean available = false;

  public synchronized int get() {
  while (available == false) {
  try {
  wait();
  } catch (InterruptedException e) { }
  }
  available = false;
  notifyAll();
  return contents;
  }

  public synchronized void put(int value) {
  while (available == true) {
  try {
  wait();
  } catch (InterruptedException e) { }
  }
  contents = value;
  available = true;
  notifyAll();
  }
  }

  public class Consumer extends Thread {
  private CubbyHole cubbyhole;
  private int number;

  public Consumer(CubbyHole c, int number) {
  cubbyhole = c;
  this.number = number;
  }

  public void run() {
  int value = 0;
  for (int i = 0; i < 10; i++) {
  value = cubbyhole.get();
  System.out.println("Consumer #" + this.number
  + " got: " + value);
  }
  }
  }

 


察看评论详细内容 我要发表评论
作者笔名 简短内容 发表时间
:

键盘也能翻页,试试“← →”键

关注我们

最新资讯离线随时看 聊天吐槽赢奖品