-1

I have written this program:


public class ThreadWithNoRunnable {
    public static void main(String[] args) {
        class MyRunnable implements Runnable {
            @Override
            public void run() {
                System.out.println("This is work getting progressed");
            }
        }
        MyRunnable r = new MyRunnable();
        Thread t = new Thread();
        t.start();
    }
}

I created a Thread object with zero argument constructor. How do I pass my Runnable object to this thread t object, so that it executes run() of MyRunnable. If this isn't possible,then why we have a zero argument Thread consutuctor?

CuriousMind
  • 8,301
  • 22
  • 65
  • 134
  • 1
    Does this answer your question? [Thread class empty constructor](https://stackoverflow.com/questions/9244147/thread-class-empty-constructor) – Savior May 24 '20 at 17:11
  • 1
    Or this one [Why would anyone ever use the Java Thread no argument constructor?](https://stackoverflow.com/questions/7572527/why-would-anyone-ever-use-the-java-thread-no-argument-constructor) – Savior May 24 '20 at 17:11
  • 1
    And the canonical [“implements Runnable” vs “extends Thread” in Java](https://stackoverflow.com/questions/541487/implements-runnable-vs-extends-thread-in-java). There's no way to set the `Thread` instance's work (`run` or `Runnable`) after it's be instantiated. – Savior May 24 '20 at 17:13
  • Thanks everyone for your help. I was trying to understand why there is default constructor with which a Thread object can be created and then later we can't be able to pass any custom Runnable Object. My intentions isn't to subclass Thread and override run(), rather was seeing if there is something I don't understand. Thanks everyone. – CuriousMind May 24 '20 at 20:51

1 Answers1

-3

I guess what you might want is a subclass of Thread:

public class ThreadWithNoRunnable extends Thread {
    public static void main(String[] args) {
        start(); //`this` is `Thread`, so it has `start`
    }

    //`run` will be the entry point on the background thread
    public void run() {
        System.out.println("This is work getting progressed");
    }
}

Pretty much same results, but less typing.

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281