Trying to create a inner class that implement Runnable interface, got error: non static variable can not be referred from a static context
Trying to create a inner class that implement Runnable interface, got error: non static variable can not be referred from a static context
我正在尝试提出一个实现 Runnable 接口的内部 class,在 main 方法中创建并启动一个新线程。
然而,IDE 一直告诉我
Error:
non static variable can not be referred from a static context
我不太清楚为什么会这样。
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
}
}
public static void main(String[] args) {
Test test = new Test();
Thread t = new Thread(test.new MyClass());
t.start();
}
你需要这样使用它。
我正在尝试提出一个实现 Runnable 接口的内部 class,在 main 方法中创建并启动一个新线程。
然而,IDE 一直告诉我
Error:
non static variable can not be referred from a static context
我不太清楚为什么会这样。
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
}
}
public static void main(String[] args) {
Test test = new Test();
Thread t = new Thread(test.new MyClass());
t.start();
}
你需要这样使用它。