new关键字用于创建对象而不分配对象引用

目前我在java中引用Thread类。所以我遇到了一个程序,其中创建了对象而没有引用对象reference.can任何人解释这个概念

这是代码

// Create a second thread. class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } 

主体计划

 class ThreadDemo { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } 

这里new用于创建线程而不引用任何对象引用。不应该像代码那样

NewThread ob = new NewThread(); 而不只是新的NewThread(); 在主要方法

“new NewThread()”创建一个新对象,调用它的构造函数。 构造函数启动一个线程。 很简单。 新的Thread对象保持“实时”(即,它不会被垃圾回收),只要它继续运行,因为从线程的堆栈中引用了Thread对象。

代码包含bug的种子。 NewThread构造函数泄漏“this”。 也就是说,它将其“this”引用传递给另一个对象(新的Thread对象),这意味着新的Thread对象的方法可能在NewThread完全初始化之前可以看到NewT​​hread。 在这种情况下,这可能是一个良性错误,因为NewThread对象似乎没有任何状态,但在更复杂的程序中,从构造函数中泄漏“this”会产生严重后果。