简体   繁体   中英

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? 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; ', 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 ).

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 .

Instead instantiate the Thread and pass the runnable instance to the constructor.

sample

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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