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

时间:2014-05-22 16:12:08

标签: java multithreading new-operator

目前我在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用于创建线程而不引用任何对象reference.shouldn不是像

这样的代码

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

1 个答案:

答案 0 :(得分:1)

"新的NewThread()"创建一个新对象,调用其构造函数。构造函数启动一个线程。很简单。新的Thread对象仍然是" live" (即,它不会被垃圾收集),只要它继续运行,因为从线程的堆栈中引用了Thread对象。

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

相关问题