如何在main()中创建线程

时间:2011-08-02 11:33:26

标签: java static

我有一个非常简单的线程程序。假设我希望线程在某些代码之后(即在程序中间)启动。我如何实现这一目标?

当我尝试在代码(下面给出的代码)之后的main()中启动线程时,它显示错误:非静态变量,这不能从静态上下文引用。

public class Main {

    public class MyThread implements Runnable {

       public void run() {
        //do something
       }
    }

    Thread t1 = new Thread (new MyThread());

    public static void main(String[] args) {
        // some code
        t1.start();
        //some code
    }
}

有人可以告诉我如何纠正错误。

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:4)

如果您不需要访问Thread之外的main变量,那么正确的解决方案就是使用本地变量:

public static void main(String[] args) {
     // some code
     Thread t1 = new Thread (new MyThread());
     t1.start();
     //some code
}

否则,您要么需要t1 static 让您的代码在非静态方法中运行(即创建您main课程的一个实例,并使用main调用的方法完成您的实际工作。

答案 1 :(得分:4)

我认为你想在main函数中实例化你的线程,因为它是一个静态函数。

 public class Main {

 public class MyThread implements Runnable {

    public void run() {
     //do something
    }
 }
     public static void main(String[] args) {
         Thread t1 = new Thread (new MyThread());

         // some code
         t1.start();
         //some code

     }
 }