-2

So I'm learning java and I kinda got confused here... So while learning threads I learned that it is necessary to extend Thread class or implement Runnable class. And while going through this program Thread.sleep() is used without doing any of the above process.

link: http://www.abihitechsolutions.com/applets-mini-project-in-java-free-source-code/

Can someone explain me what is going on?

renatodamas
  • 16,555
  • 8
  • 30
  • 51
  • 1
    If the tutorial you are using tells you to extend `Thread` find a new one. Typically you implement `Runnable` (probably as a lambda method) and pass that to a `Thread` instance (or to something that manages threads). Also `Thread.sleep` isn't useful in real programs - you'll want a timer of some sort. – Tom Hawtin - tackline Oct 08 '18 at 14:22
  • No. `Thread.sleep()` is a _[static method](https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/)_ in the `Thread` class. You do not need to have a `Thread` instance to invoke it. – Solomon Slow Oct 08 '18 at 14:23

3 Answers3

1

It is much better to implement Runnable than to extends Thread. Thread.sleep() is a static method so you can call it from anywhere.

class RunMe implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("Hello");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Bear in mind that all Java code runs in a thread so calling Thread.sleep() can be done anywhere.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
1

By using Thread.sleep(X) actually you are pausing execution for time X.

This is suitable for sending requests to servers or database. Nobody wants to send a huge request to DB or server in one time.

Making small portions is always reasonable. You can divide your requests and send them by waiting specified time duration.

This is one of the important usages of Thread.sleep()

There is a much proper way to handle thread pausing which is wait/notify. I suggest using it. You can check from there; https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html

kaan bobac
  • 729
  • 4
  • 8
0

The reason why you can use Thread.sleep without actually creating a thread is because the main program is also running on a thread. You're simply calling sleep on the main thread. When you call Thread.sleep, java will figure out for you which thread it is actually running on.

Thomas
  • 11
  • 2
  • No! The only reason is that `Thread.sleep` is a static method. – Seelenvirtuose Oct 08 '18 at 14:33
  • @Seelenvirtuose You, are right when coming to scope. What ```Thomas``` explained is see the difference between two codes 1 -> https://onlinegdb.com/SJ_Ba1Uxv ans 2 -> https://onlinegdb.com/ryyPTk8xP – Sathvik Jul 22 '20 at 16:47