【问题标题】:Trying to create a inner class that implement Runnable interface, got error: non static variable can not be referred from a static context [duplicate]尝试创建一个实现 Runnable 接口的内部类,出现错误:无法从静态上下文引用非静态变量 [重复]
【发布时间】:2017-01-27 21:15:43
【问题描述】:

我正在尝试提出一个实现 Runnable 接口的内部类,在 main 方法中创建并启动一个新线程。

但是,IDE 一直告诉我

错误:

不能从静态上下文中引用非静态变量

我不确定为什么会这样。

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
        
    }
}

【问题讨论】:

  • 静态类 MyClass 实现 Runnable {

标签: java multithreading concurrency main runnable


【解决方案1】:
public static void main(String[] args) {
Test test = new Test(); 
    Thread t = new Thread(test.new MyClass());         
    t.start(); 
}

你需要这样使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 2018-01-04
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多