| 以下程序的意思是,有一个仓库资源为10,少于10的时候不能取,大于10的时候往仓库存每次存一个资源,取的时候每次取4个资源。然后报了这个错误at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:485)
 at com.lucus.lock.InputBox.run(Syt.java:45)
 at java.lang.Thread.run(Thread.java:619)。不知道哪儿出问题了。
 
 
 package com.lucus.lock;
 public class Syt {
 public static void main(String[] args) {
 Box b = new Box();
 InputBox in = new InputBox(b);
 OutputBox out = new OutputBox(b);
 Thread ins = new Thread(in);
 Thread outs = new Thread(out);
 ins.start();
 outs.start();
 }
 }
 class Box {
 private int boxs = 10;
 public int getBoxs() {
 return boxs;
 }
 public void setBoxs(int boxs) {
 this.boxs = boxs;
 }
 }
 class InputBox implements Runnable {
 private Box boxs;
 public InputBox(Box boxs) {
 this.boxs = boxs;
 }
 @Override
 public void run() {
 while (true) {
 synchronized (boxs) {
 if (boxs.getBoxs() < 10) {
 System.out.println("仓库的资源少于10,正在存,别的线程需要等待,倉庫剩下資源為"+this.boxs.getBoxs());
 this.boxs.setBoxs(this.boxs.getBoxs() + 1);
 } else {
 try {
 this.wait();
 } catch (InterruptedException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 this.notify();
 }
 }
 }
 }
 }
 class OutputBox implements Runnable {
 private Box boxs;
 public OutputBox(Box boxs) {
 this.boxs = boxs;
 }
 @Override
 public void run() {
 while (true) {
 synchronized (boxs) {
 if (this.boxs.getBoxs() < 10) {
 try {
 this.wait();
 } catch (InterruptedException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 this.notify();
 } else {
 this.boxs.setBoxs(this.boxs.getBoxs() - 4);
 System.out.println("正在拿資源,剩下資源為"+this.boxs.getBoxs());
 }
 }
 }
 }
 }
 
 |