如何从 Java 应用程序的 Main 方法运行线程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6878426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I run thread from Main method in Java application?
提问by user482594
I believe variables used in static main
method should be also static
as well.
The problem is that I cannot use this
in this method at all. If I remember correctly, I have to initiate thread with commnad myThread = new ThreaD(this)
.
我相信static main
方法中使用的变量也应该如此static
。问题是我根本无法使用this
这种方法。如果我没记错的话,我必须用 commnad 启动线程myThread = new ThreaD(this)
。
The below codes produces an error because I used this
in thread initiation.
What have I done wrong here?
以下代码会产生错误,因为我this
在线程启动中使用过。我在这里做错了什么?
package app;
public class Server implements Runnable{
static Thread myThread;
public void run() {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
System.out.println("Good morning");
myThread = new Thread(this);
}
}
回答by Nathan Hughes
You can't use this
because main is a static method, this
refers to the current instance and there is none. You can create a Runnable object that you can pass into the thread:
您不能使用,this
因为 main 是一个静态方法,this
指的是当前实例并且没有。您可以创建一个可以传递给线程的 Runnable 对象:
myThread = new Thread(new Server());
myThread.start();
That will cause whatever you put in the Server class' run method to be executed by myThread.
这将导致 myThread 执行您在 Server 类的 run 方法中放置的任何内容。
There are two separate concepts here, the Thread and the Runnable. The Runnable specifies what work needs to be done, the Thread is the mechanism that executes the Runnable. Although Thread has a run method that you can extend, you can ignore that and use a separate Runnable.
这里有两个独立的概念,Thread 和 Runnable。Runnable 指定了需要完成哪些工作,Thread 是执行 Runnable 的机制。尽管 Thread 有一个可以扩展的 run 方法,但您可以忽略它并使用单独的 Runnable。
回答by Jason Wheeler
Change new Thread(this)
to new Thread(new Server())
:
更改new Thread(this)
为new Thread(new Server())
:
package app;
public class Server implements Runnable{
static Thread myThread;
public void run() {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
System.out.println("Good morning");
myThread = new Thread(new Server());
}
}
回答by fatnjazzy
class SimpleThread extends Thread {
public SimpleThread(String name) {
super(name);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " thread: " + getName());
try {
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
System.out.println("DONE! thread: " + getName());
}
}
class TwoThreadsTest {
public static void main (String[] args) {
new SimpleThread("test1").start();
new SimpleThread("test2").start();
}
}