1

Is it possible to use the Thread class in another class without implementing Runnable interface or without extending the the Thread class itself?

Here is a code that invokes the sleep method on Thread.

public class SleepMessages {
    public static void main(String args[])
        throws InterruptedException {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };

        for (int i = 0;
             i < importantInfo.length;
             i++) {
            //Pause for 4 seconds
            Thread.sleep(4000);
            //Print a message
            System.out.println(importantInfo[i]);
        }
    }
}
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
Tadele Ayelegn
  • 4,126
  • 1
  • 35
  • 30
  • 1
    You can pass a `Runnable` to it instead of implementing it – Vince Dec 31 '14 at 06:39
  • you can use `OS` level feature called `fork()` of linux if you donot want to use `runnable/Thread` class – Bhargav Modi Dec 31 '14 at 06:41
  • @BhargavModi You can use it how? in Java? – user207421 Dec 31 '14 at 06:41
  • @EJP [have a look on this](http://stackoverflow.com/a/526287/2749470) – Bhargav Modi Dec 31 '14 at 06:42
  • @BhargavModi Have a look at it why? No `fork()` call there. – user207421 Dec 31 '14 at 06:43
  • @EJP you can also write `fork logic` in sh file and just execute a sh file using `Runtime.getRuntime().exec(myShellScript);` – Bhargav Modi Dec 31 '14 at 06:45
  • @BhargavModi If you're recommending the `ProcessBuilder`, why not do so, instead of irrelevantly mentioning 'OS level feature called `fork()`? – user207421 Dec 31 '14 at 06:46
  • @EJP it was just a idea if you want use multithreading feature without using `runnable/callable/Thread` entities and `fork` is some what more explained in linux as creating `child processes`. and regarding how to execute it there many ways in java so I had just shared that link – Bhargav Modi Dec 31 '14 at 06:50
  • @BhargavModi - You will have no control over the OS level threads whatsoever if you use `ProcessBuilder`. `ProcessBuilder` should not be used to execute threads. Java provides a better way of handling threads. Use it:) – TheLostMind Dec 31 '14 at 06:54
  • @TheLostMind frankly speaking I had just provided an way to achieve multithreading, and using `processBuilder` is just a way and in previous comment I had also mentioned that there are other ways to achieve it :) – Bhargav Modi Dec 31 '14 at 06:56
  • 1
    @BhargavModi - If he uses ProcessBuilder, it will not be called *MultiThreading* anymore :) – TheLostMind Dec 31 '14 at 07:02
  • @TheLostMind rather getting into prolonged discussion over `ProcessBuilder` let me sum it up as just call a shell script using java. that's it :) – Bhargav Modi Dec 31 '14 at 07:06

3 Answers3

3

Yes it is possible, your code is a proof of this. You can always use static members of a given class without instanciating the class. Roughly, in Java every class is an object that you don't have to instanciate, on which you can call its static methods.

What you can't do is to create a useful Thread without implementing the Runnable interface or extending the Thread class. (You can create a Thread without doing so by instanciating the Thread class directly, but such a thread will not be useful).

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
0

sleep() is a static method in class Thread. When you call Thread.sleep(), the current thread is used. So, yes, at any point of time, an executing program should have at least one active/running thread. Calling Thread.sleep() will make the Current Thread sleep. Here, you are not creating a new thread. You are actually using an existing thread. You need to either extend Thread class or implement Runnable for your Custom class to behave as a Thread.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • so is the Thread class was passed implicitly here? If it is, does that mean every java code has Thread class in it? – Tadele Ayelegn Dec 31 '14 at 06:51
  • @tadtab - No. The `Thread` class wasn't *implicitly* passed. As a matter of fact, the *Current Thread* was implicitly used. Check [Thread,sleep()](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep(long)) – TheLostMind Dec 31 '14 at 07:01
  • I am not sure if I understood the concept well but I read something about every java application has at least one thread, which is the main thread what does that mean? – Tadele Ayelegn Dec 31 '14 at 07:08
  • @tadtab - See, every java application runs in it own process with its own JVM. Every process must have atleast one thread in it called the *main* thread. This is the thread which starts execution as soon as the application starts. Other threads can be created and started using this thread. So when you create a thread, say using- `new Thread(new Runnable..` the main thread creates a new thread. – TheLostMind Dec 31 '14 at 07:12
  • @ TheLostMind, Ok so to have a main Thread, the class has to either implement Ruunable or extend the Thread class first. right? – Tadele Ayelegn Dec 31 '14 at 07:22
  • @tadtab - Yes.. You can.. The Operating systems starts each application in its own process. Each process implicitly has a Thread known as the main thread. In your case the thread which is being used is the main thread, but sleep works on *current* thread (a main thread need not always be the current thread). – TheLostMind Dec 31 '14 at 07:35
  • @ TheLostMind thanks a lot, this http://docs.oracle.com/javase/tutorial/getStarted/application/ hello world program has to have a main Thread to run as an application? I mean i got stuck on understanding the basics. – Tadele Ayelegn Dec 31 '14 at 07:35
  • @tadtab - Yes. Use `System.out.println(Thread.currentThread());` in your `main()` method to see it for yourself :) – TheLostMind Dec 31 '14 at 07:36
  • 1
    _"Ok so to have a main Thread, the class has to either implement Ruunable or extend the Thread class first. right?"_ @tadtab, Maybe. Most Java Virtual Machines are C programs that implement something called the Java Native Interface (JNI). The JNI allows C-code to call Java methods and create new Java threads. The main thread of a Java program is created by a JNI call, and when a thread is created in that way, it will always have a `Thread` object, but it can start in any method of any class. It does not have to start in the Thread object's run() method. – Solomon Slow Dec 31 '14 at 17:10
  • @james large - I never said the first line. .. I was just saying that an application must always have a main thread... Any application either with or without java must have a main thread. . It is a OS related concept. . Yes, creating and starting custom or new threads involve calls like start0 which is a native call. . – TheLostMind Dec 31 '14 at 17:33
  • No, it is not invoking sleep on the current thread. It is invoking a static method sleep on the class. (but this happens in the current thread, obviously). The main() method is called by the JRE with the main thread. This thread is created by the launcher. (and a few other threads, which you do not see in this example). – eckes Dec 31 '14 at 20:46
  • @eckes - Modified the answer to make it clearer. When the JVM starts there will be only one main thread, the other threads (like the one for GC) will be daemon threads. – TheLostMind Jan 01 '15 at 04:58
0

You can create an instace of Thread pass a Runnable to it instead of implementing: (Java 8)

Thread thread = new Thread(() -> {
       //code here
});

public class SleepMessages {
    public static void main(String args[]) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            public void run() {
                String importantInfo[] = {
                    "Mares eat oats",
                    "Does eat oats",
                    "Little lambs eat ivy",
                    "A kid will eat ivy too"
                };

                for (int i = 0; i < importantInfo.length; i++) {
                    //Pause for 4 seconds
                    Thread.sleep(4000);
                    //Print a message
                    System.out.println(importantInfo[i]);
                }
            }
        });

        thread.start();
    }            
}
Vince
  • 14,470
  • 7
  • 39
  • 84
  • Don't know what you mean by "instead of implementing". The `//code here` comment in your example is in the run() method of an _anonymous inner class_ that implements Runnable. – Solomon Slow Dec 31 '14 at 16:59
  • @jameslarge Thought he was referring to his class, not an anonymous class. Better? – Vince Dec 31 '14 at 19:36