class ManTou{
int id;
ManTou(int id){
this.id = id;
}
public String toString(){
return "ManTou" + id;
}
}class Basket{
int index = 0;
ManTou[] m = new ManTou[6];


public synchronized void push(ManTou mt){

while(index == m.length){
try{
this.wait();
} catch (InterruptedException e){
e.printStackTrace();
}
}
this.notify();
m[index] = mt;
index ++;
}

public synchronized ManTou pop(){

while(index == 0){
try{
this.wait();
} catch (InterruptedException e){
e.printStackTrace();
}
}
this.notify();
index --;
return m[index];
}
}class Producer implements Runnable{
Basket b = null;
Producer(Basket b){
this.b = b;
}


public void run(){
   for(int i=1; i<20; i++) {
ManTou m = new ManTou(i);
b.push(m);
System.out.println("We have produce"+m+"ManTou!!!!!!");
try {
Thread.sleep((int)(Math.random() * 200));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}class Consumer implements Runnable{
Basket b = null;
Consumer(Basket b){
this.b = b;
}

public void run(){
for (int i = 1;i < 20;i ++){
ManTou m = b.pop();
System.out.println("We have consume"+m+"ManTou!!!!!!");
try{
Thread.sleep((int)(Math.random()*1000));
} catch (Exception e){
e.printStackTrace();
}
}
}
}
public class ConsumerProducer {
public static void main(String args[]){
Basket b =new Basket();
Producer p = new Producer(b);
Consumer c = new Consumer(b);
new Thread(p).start();
new Thread(c).start();

}
}
代码如上。在命令行的显示为无法找到Math类的random方法。
在Eclipse上,就是We have produceManTou1ManTou!!!!!!
We have produceManTou2ManTou!!!!!!
We have produceManTou3ManTou!!!!!!
We have produceManTou4ManTou!!!!!!
We have produceManTou5ManTou!!!!!!
We have produceManTou6ManTou!!!!!!谢谢各位大大的回复!threadeclipse

解决方案 »

  1.   

    检查一下你是否导入了random方法
      

  2.   

    Math类是在java.lang包里面的, 不需要在文件中添加导入语句,估计是你的classpath没写对
      

  3.   

    时而有时而无的出现Math方法找不到的情况。
    这两天有些事帖子没顾上,抱歉。
    昨天蓝屏了一次,我关机了今天下午才开的机,然后发现javac又找不到了,貌似环境变量设置是出了问题:
    JAVA_HOME :    C:\Program Files\Java\jdk1.7.0_09
    CLASSPATH :    .;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar;
    Path    :    %JAVA_HOME%\bin;%JAVA_HOME%\jre\bin;C:\Program Files (x86)\DBank\ClickUp;C:\Program Files (x86)\DBank\ClickUp
    刚刚改了,因为接触时间不长,所以对环境变量的设置这块还不是很熟悉。
    谢谢
      

  4.   

    像上面说的,Math本身是lang下面的吧,不需要导入吧?
      

  5.   

    包确实不需要导入
    但是不代表不需要import啊、
      

  6.   

    最好把命令行报错的原文发一下如果是直接报找不到random方法,这就有点奇怪了,因为如果找不到rt.jar之类,它会报更高层的错误,比如找不到rt.jar或者找不到java.lang.Object之类对于寻找rt.jar等lib内容,不需要依赖ClassPath的设定,只要能找到java.exe命令,就能根据相对固定路径找到lib