首页 > 解决方案 > 在 Java 线程代码中“忽略新实例”警告

问题描述

所以我尝试在 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.");
    }
}

标签: javamultithreadingnetbeanscompiler-warnings

解决方案


推荐阅读