你load没初始化,去调change肯定时Nullpointer了

解决方案 »

  1.   

    倒了。
    你这里的load.change(count);的这个load没有实例话,是个空对象阿。他不是着不到count而是找不到load。你可以这样改的
    class Counter extends Thread{
       CounReload load=new CounReload();
       String name;
    public static int count=0;
    ......
      

  2.   

    import java.io.*;
    public class bean5 {
    public static void main(String args[]){
        new Counter("A");
        new Counter("B");
        new Counter("C");
        new Counter("D");
        try{Thread.sleep(10000);}
         catch(InterruptedException e){}
      }
    }
    class Counter extends Thread{
       CounReload load;
       String name;
       int count=0;
       Counter(String name){
         this.name=name;
         new Thread(this,"dfds").start();
       }
       public void run(){
         while(true){
         System.out.print(name+" ");
         new CounReload().change(count++);     try{Thread.sleep(100);}
         catch(InterruptedException e){}
         }
       }
    }
    class CounReload{
       synchronized void change(int c){
         System.out.println("count:    "+c);
        }
    }
      

  3.   

    /***
      名称和 count 的数值有时会错开, 你可能需要吧名字输出也加到同步方法中去. **/
    import java.io.*;
    public class T1 {
      public static void main(String args[]){
        CounReload load = new CounReload();
        new Counter(load, "A");
        new Counter(load, "B");
        new Counter(load, "C");
        new Counter(load, "D");
        
        try{
          Thread.sleep(10000);
        }catch(InterruptedException e){
        }
        
        System.exit(0);
      }
    }class Counter extends Thread{
       CounReload load;
       String name;   Counter(CounReload load , String name){
         this.name=name;
         this.load = load;
              
         new Thread(this,"dfds").start();
       }
       
       
       public void run(){
         while(true){
           System.out.print(name+" ");
           load.change();             
           
           try{
             Thread.sleep(100);
           }catch(InterruptedException e){
           }
         }
       }
    }
    class CounReload{
       // define count here   
       int count = 0; 
       
       
       // synchronized method
       synchronized int change(){      
         count++;
         System.out.println("count:    "+count);
         return count;
       }
    }
      

  4.   

    多谢楼上的兄弟,你给我的程序就是我想要的。
    我还想问一下,为什么不能把count定义在T1内中?
    我把它定义成public 也不行,
    不是说public 在其他类中也是可用的吗?为什么它还说找不到变量count?
      

  5.   

    可以放在 T1 中, 不过存取要使用 obj.count (obj 是T1 的句柄)来存取, 不如放在 CounReload 方便,它本身应该是 CounReload 的一部分。