其实,这涉及到内部类的访问问题:
你只须将内部类定义为static即可,即代码修改为:
public class test
{
    public static void main(String[] args)
    {
        Thread t=new Thread(new CounterBehavior());
        t.start();
    }
    
->(改为static属性)static class CounterBehavior implements Runnable
    {
        public void run()
        {
            for(int i=0;i<100;i++)
            {
                try
                {
                    System.out.println(i);
                    Thread.sleep(1000);
                }
                catch(InterruptedException e)
                {}
            }
        }
    }
}
为什么?
因为为正确理解static在应用于内部类时的含义,必须记住内部类的对象默认持有创建它的那个封装类的一个对象的句柄。然而,假如我们说一个内部类是static的,这种说法却是不成立的。static内部类意味着:
(1) 为创建一个static内部类的对象,我们不需要一个外部类对象。
(2) 不能从static内部类的一个对象中访问一个外部类对象。
但在存在一些限制:由于static成员只能位于一个类的外部级别,所以内部类不可拥有static数据或static内部类。
倘若为了创建内部类的对象而不需要创建外部类的一个对象,那么可将所有东西都设为static。为了能正常工作,同时也必须将内部类设为static参考<<thinking in java>>

解决方案 »

  1.   

    public class test
    {
        public static void main(String[] args)
        {
    test tin = new test();
            Thread t=new Thread(tin.cb);
            t.start();
        }
    CounterBehavior cb=new CounterBehavior();
        class CounterBehavior implements Runnable
        {
            public void run()
            {
                for(int i=0;i<100;i++)
                {
                    try
                    {
                        System.out.println(i);
                        Thread.sleep(1000);
                    }
                    catch(InterruptedException e)
                    {}
                }
            }
        }
    }
      

  2.   

    static 将程序空间放在堆中,有点类似全局
      

  3.   

    将 Thread t=new Thread(new CounterBehavior()); 
    改为: Thread t = new Thread( new test().new CounterBehavior() );
    即可。