因此,我尝试在NetBeans IDE 11.1中运行此代码,它显示“忽略新实例”错误。我的标准教科书在以下代码中没有提及警告。为什么会显示此错误,我该怎么解决?并在构造函数中启动新线程?也有问题吗?
=======
class NewThread1 implements Runnable {
Thread t1;
NewThread1() {
t1 = new Thread();
System.out.println("Thread : " + t1.getName());
t1.start(); //Starting new thread in a constructor
}
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println("When NewThread.i = " + i);
t1.sleep(500);
}
} catch (Exception e) {
System.out.println("t1 interrupted.");
}
System.out.println("t1 ends.");
}
}
public class NewClass1 {
public static void main(String[] args) {
new NewThread1(); //New Instance Being Ignored
try {
for (int i = 0; i < 5; i++) {
System.out.println("When main.i = " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("main thread interrupted.");
}
System.out.println("Main thread end.");
}
}