如何从 Java 应用程序中的 Main 方法运行线程?
我相信 static main
方法中使用的变量也应该是 static
。 问题是我根本无法在此方法中使用 this
。如果我没记错的话,我必须使用 commnad myThread = new ThraD(this)
启动线程。
下面的代码会产生错误,因为我在线程启动中使用了 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);
}
}
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)
.
The below codes produces an error because I used this
in thread initiation.
What have I done wrong here?
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能使用
this
因为 main 是一个静态方法,this
引用当前实例并且没有。您可以创建一个可传递到线程中的 Runnable 对象:这将导致您在 Server 类的 run 方法中放入的任何内容都由 myThread 执行。
这里有两个独立的概念,线程和可运行。 Runnable指定需要完成什么工作,Thread是执行Runnable的机制。尽管 Thread 有一个可以扩展的 run 方法,但您可以忽略它并使用单独的 Runnable。
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:That will cause whatever you put in the Server class' run method to be executed by myThread.
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.
将
new Thread(this)
更改为new Thread(new Server())
:Change
new Thread(this)
tonew Thread(new Server())
: