本帖最后由 潘才新 于 2013-8-29 01:12 编辑
package com.qindazhong;
import java.util.*;
class MyNumber1{
private List<Integer> list = new ArrayList<Integer>();
public void push(int i){
synchronized(this){
if(!list.isEmpty()){
try{
Thread.sleep(100);
}
catch(Exception e){}
}else{
list.add(new Integer(i));
}
}
}
public void pop(){
synchronized(this){
if(list.isEmpty()){
try{
Thread.sleep(100);
}catch(Exception e){}
}else{
Iterator<Integer> it = list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
list.clear();
}
}
}
}
class Productor implements Runnable{
private MyNumber1 myNumber;
public void run(){
myNumber.push(new Random().nextInt(new Integer(9)));
}
}
class Consummer implements Runnable{
private MyNumber1 myNumber ;
public void run(){
myNumber.pop();
}
}
public class Demo3 {
public static void main(String[] args){
Thread d1 = new Thread(new Productor());
Thread d2 = new Thread(new Consummer());
d1.start();
d2.start();
}
}
跑出的异常是,空指正异常,run方法中的语句 myNumber.push(new Random().nextInt(new Integer(9)));
和语句myNumber.pop();,怎么会出现空指针异常啊,纠结得我都睡不着啊!!!!!!!!
|