如何启动匿名线程类 [英] How to start anonymous thread class
本文介绍了如何启动匿名线程类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码段:
public class A {
public static void main(String[] arg) {
new Thread() {
public void run() {
System.out.println("blah");
}
};
}
}
在这里,如何在不创建线程类实例的情况下为线程调用start()
方法?
Here, how do I call the start()
method for the thread without creating an instance of the thread class?
推荐答案
您已经在创建Thread类的实例-您只是对它不做任何事情.您甚至可以不使用局部变量来调用start()
:
You're already creating an instance of the Thread class - you're just not doing anything with it. You could call start()
without even using a local variable:
new Thread()
{
public void run() {
System.out.println("blah");
}
}.start();
...但是我个人通常会将其分配给局部变量,然后执行您要执行的其他任何操作(例如,设置名称等),然后启动它:
... but personally I'd normally assign it to a local variable, do anything else you want (e.g. setting the name etc) and then start it:
Thread t = new Thread() {
public void run() {
System.out.println("blah");
}
};
t.start();
这篇关于如何启动匿名线程类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文