多线程Java多线程演示不工作
我正在写一个小程序,看看如何在Java中运行多个线程。不确定为什么我没有得到任何输出:
class NuThread implements Runnable {
NuThread() {
Thread t = new Thread(this, "NuThread");
t.start();
}
public void run() {
try {
for (int i=0; i<5; i++) {
Thread th = Thread.currentThread();
System.out.println(th.getName() + ": " + i);
Thread.sleep(300);
}
} catch (InterruptedException e) {
Thread th = Thread.currentThread();
System.out.println(th.getName() + " interrupted.");
}
}
}
public class MultiThreadDemo {
public static void main(String[] args) {
NuThread t1, t2, t3;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main interrupted.");
}
}
}
# 1 楼答案
你没有创建任何
NuThread
的实例。这一行:。。。只声明了三个变量。它不会创建任何实例。你需要这样的东西:
话虽如此,让构造函数启动一个新线程本身就有点奇怪。。。最好将其移除,只需:
请注意,可以对所有三个线程使用相同的
Runnable
,因为它们实际上不使用任何状态# 2 楼答案
您没有创建NuThread的对象。这就是线程没有启动的原因
在构造函数中启动线程不是最好的方法,请参见here