Search code examples
javamultithreadingconcurrencyprogram-entry-pointrunnable

Trying to create a inner class that implement Runnable interface, got error: non static variable can not be referred from a static context


I'm trying to come up with a inner class that implement Runnable interface, create and start a new thread in the main method.

However, IDE keeps telling me that

Error:

non static variable can not be referred from a static context

I'm not exactly sure why this is happening.

public class Test {
    
    class MyClass implements Runnable {
        @Override
        public void run(){
            System.out.println("hello");
        }
    }
    
    public static void main(String[] args) {
        Thread t = new Thread(new MyClass()); //error: non static variable can not be referred from a static context
        
    }
}

Solution

  • public static void main(String[] args) {
    Test test = new Test(); 
        Thread t = new Thread(test.new MyClass());         
        t.start(); 
    }
    

    You need use it this way .