新关键字用于创建对象,而无需分配给对象引用 [英] new Keyword is used for creating object without assigning to an object reference

查看:63
本文介绍了新关键字用于创建对象,而无需分配给对象引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在用Java引用Thread类,因此遇到了一个创建对象的程序,而没有引用对象引用.任何人都可以解释这个概念

Currently i am referring Thread class in java .so i came across a program in which object is created without referring to to the object reference.can anyone explain the concept

这是代码

// 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用于创建线程而不引用任何对象引用.不应是

here new is used for creating thread without reference to any object reference.shouldn't be the code like

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

NewThread ob =new NewThread(); instead of just new NewThread(); in the main method

推荐答案

"new NewThread()"创建一个新对象,并调用其构造函数.构造函数启动一个线程.很简单.只要新线程对象继续运行,它就会保持活动"状态(即不会被垃圾回收),因为从线程堆栈中引用了该线程对象.

The "new NewThread()" creates a new object, calling its constructor. The constructor starts a thread. Simple enough. The new Thread object remains "live" (i.e., it will not be garbage collected) as long as it continues to run because there is a reference to the Thread object from the thread's stack.

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

The code contains the seed of a bug though. The NewThread constructor leaks "this". That is to say, it passes its "this" reference to another object (the new Thread object) which means that methods of the new Thread object potentially can see the NewThread before the NewThread has been completely initialized. That's probably a benign error in this case because the NewThread object doesn't appear to have any state, but in a more complicated program, leaking "this" from a constructor can have serious consequences.

这篇关于新关键字用于创建对象,而无需分配给对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆