简体   繁体   English

方法局部内部类的作用域

[英]method local inner classes scope

I have following code : 我有以下代码:

class MyThread{
      static volatile java.io.PrintStream s=System.out;
      public static void main(String args[]){
        Runnable r1=new Runnable(){
          public void run(){
            synchronized(s){
              for(int i=0; i<100; i++)
                 system.out.println("in r1");
            }
          }
        };
        Runnable r2=new Runnable(){
          public void run(){
            synchronized(s){
              for(int i=0; i<100; i++)
                 system.out.println("in r2");
            }
          }
        };
        Thread t1=(Thread)r1;
        Thread t2=(Thread)r2;
        t1.start();
        t2.start();
      }
}

My question is : as r1 and r2 are method local inner classes , how could they access 's' as it is not final? 我的问题是:由于r1和r2是方法局部内部类,因此它们如何访问不是最终的's'? code does not give any error. 代码没有给出任何错误。

but it throws exception at line ' Thread t1=(Thread)r1; Thread t2=(Thread)r2; 但是它会在' Thread t1=(Thread)r1; Thread t2=(Thread)r2; Thread t1=(Thread)r1; Thread t2=(Thread)r2; ', why so? ', 为什么这样?

Thanks in advance 提前致谢

In general, inner classes can access non final members of their enclosing instance. 通常,内部类可以访问其封闭实例的非最终成员。

They can't access non-final local variables declared in the scope in which they are declared. 他们无法访问在其声明范围内声明的非最终局部变量。

That said, your anonymous classes are defined within a static method, so they don't have an enclosing instance, but they are accessing a static class member, so that's also valid. 也就是说,您的匿名类是在静态方法中定义的,因此它们没有封闭的实例,但是它们正在访问静态类成员,因此这也是有效的。

As for the exception, you are trying to cast your anonymous instances to Thread , even though their type is not Thread (their type is Runnable ). 至于异常,您正在尝试将匿名实例转换为Thread ,即使它们的类型不是Thread(其类型为Runnable )。

What you are trying to do is probably : 您正在尝试做的可能是:

    Thread t1 = new Thread(r1);
    Thread t2 = new Thread(r2);
    t1.start();
    t2.start();

problem: 问题:

Thread t1=(Thread)r1;
Thread t2=(Thread)r2;

r1 and r2 are a Runnable not a Thread upon casting it it will generate ClassCastException . r1r2Runnable而不是Thread在转换时会生成ClassCastException

Instead instantiate the Thread and pass the runnable instance to the constructor. 而是实例化Thread并将runnable实例传递给构造函数。

sample 样品

Thread t1=new Thread(r1);
Thread t2=new Thread(r2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM