且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

新关键字用于创建对象,而无需分配给对象引用

更新时间:2023-12-03 21:09:40

"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.