问题
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
here is the code
// 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.");
}
}
Main Program
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.");
}
}
here new is used for creating thread without reference to any object reference.shouldn't be the code like
NewThread ob =new NewThread(); instead of just new NewThread(); in the main method
回答1:
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.
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.
来源:https://stackoverflow.com/questions/23812122/new-keyword-is-used-for-creating-object-without-assigning-to-an-object-reference