1

There are two things that I did not clear, one concerns the new operator, the other, the method Thread.sleep.

// 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.");
  }

I know that the new operator is used to allocate an object for example: Box refvar=new Box(); call the constructor of Box class in this case the call is new NewThread();

But I have no reference variable, I don't understand how Java call the constructor without reference variable. Normally I use: Nameofclass reference-variable-name = new NameOfConstructor();.

Another thing I do not understand is: how Java can call Thread.sleep() if there is no object with the name Thread? in this case should be: t.sleep(1000) or not?

Thanks in advance.

dotvav
  • 2,808
  • 15
  • 31
user3782573
  • 95
  • 1
  • 8

7 Answers7

3

You can call a constructor without assigning a reference to it.

In your case, the field Thread t maintains a reference to the thread, so there will be no premature garbage collection.

Thread.sleep() sleeps the current thread; i.e. the thread that is currently executing that bit of code.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

It is valid to create an object (new File()) without storing the object (File file = new File()). In that case you create the object and call the constructor but can't do anything with the result. In many cases this doesn't do much (but it could change static data or throw an exception).

In your case the constructor NewThread() actually creates a thread and starts it.

Your second question regarding Thread.sleep() actually calls the static function sleep in the class Thread, which will wait for the given time and then return. So this will actually sleep the current thread, and not another thread that you call it on. Note that even calling it on a thread object (someThread.sleep()) still sleeps the current thread and not someThread. In your example the current thread is the main thread (which is created by the JVM and eventually used to call the main function)

Thirler
  • 20,239
  • 14
  • 63
  • 92
  • Depends what you mean by "storing the object". What about this: `new Thread(() -> foo()).start();`? Or, what about `crunch(new Bunch());`? – Solomon Slow Nov 20 '15 at 15:30
  • I skipped over that part to keep the answer at an entry level. So I used the non official term storing. Basically there are several things you can do to keep an object known: store it in a local variable (on the stack), this is also what happens when you pass it to a function. You can also store it in a member variable (on the heap). Finally when starting a thread (what happens in this example) you will create a new stack and store the Runnable object on there (it can be accessed from the new thread in the Runnable object itself). – Thirler Nov 23 '15 at 07:54
1

Thread#sleep always affects only the current thread. You are not allowed to target other threads in order to put them to sleep. Calling t.sleep() results in the static method being called, which affects the current thread. Calling static methods on an instance is a bad idea, it is likely to mislead people who read the code into thinking the code is putting another thread to sleep.

Your NewThread creates a thread in the constructor. Once you start a thread it will run until it terminates, regardless of if anything else has a reference to it. Each thread is a GC root that prevents garbage collection of anything that it references. Keeping a reference to the thread would allow you to interrupt it or otherwise communicate with it.

The posted code looks like it was created by somebody who had heard that using Runnable was preferred over extending Thread, but who had missed the point about why. Having a Runnable create a thread for itself defeats the purpose of separating Runnables (the tasks that need to be executed) from the means of executing the tasks (the threads). This is not a good way to design any real code for a purpose other than causing confusion.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
1

Thread.sleep(...)

is possible because sleep is a static method which

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

according to the JavaDoc

Mark Sholund
  • 1,273
  • 2
  • 18
  • 32
1
new NewThread();

Creates a new object with no reference in your main, therefore after the creation you are no more able to access this object within main. But the object is created anyway.

Thread.sleep(1000);

Secondly, sleep is a static method, therefore you can call this method directly with the classname, you do not need to instanciate an object of thread first for this.

Xavjer
  • 8,838
  • 2
  • 22
  • 42
1

1) new ClassName() will create an instance. Even if you can't refer to it later, you can call instance methods on that instance there itself.

2) Thread class has a static method called sleep() and static method doesn't require an instance. They can directly be called using the className.methodName()

Sagar D
  • 2,588
  • 1
  • 18
  • 31
0

Generally Thread Created 2-way, 1. extends Thread class 2. implements Runnable interface.

Here, you have choose option-2, e.g. Runnable Interface.

In your code,

you have first Created new Thread(...) with new keyword, which is wrap-in Runnable object inside it.

Answer-2 :

Thread.sleep() method : it's pause current thread's execution, while executing it, current thread move to Wait/Block state from Running State of thread life-cycle. After completion of N-millisecond (here 500, i.e. 0.5 sec.). that thread again wake up it and comes to Runnable state.

Let me know, if still any query.

Vishal Gajera
  • 4,137
  • 5
  • 28
  • 55