简体   繁体   中英

How to run threads without using Runnable implementations?

I found the following excerpt in a Java Textbook:

"I've seen examples that don't use a separate 
Runnable Implementation, but Instead Just make a 
subclass of Thread and override the Thread's runO 
method. That way,you call the Thread's no-arg 
constructor when you make the new thread; 
Thread t = new Thread(); //no Runnable"

Shouldn't the last line be

Thread t = new <Some class that extends Thread class and over rides its run method>();

Am I correct?

Could somebody provide sample code that illustrates the above excerpt?

You are correct.

If you create an instance of Thread without overriding run() of supplying a Runnable , the thread would execute the default empty run() method.

I wonder if this quote is accurate, as it specifically mentions sub-classing Thread, but the code Thread t = new Thread(); clearly doesn't.

Basically you are talking about runtime polymorphism. Yes you could do that. See following exmaple:

class Flight extends Thread {
    public void run() {
        System.out.println("Hello World.. I took off");
    }
}

public static void main(String[] args) {
    Flight flight = new Flight();
    Thread myflight = new Flight();//See how i used runtime polymorphism.
    flight.start();
    myflight.start();
}

You can override the run method "inline" with an anonymous subclass:

new Thread() {
    public void run() {
        doStuffInPaarralel();
    }
}.start();

Not that there are a lot of advantages to this over supplying a separate Runnable class. You rearely need a thread, that just does one thing and dies, it's kinda wasteful. A better way is to use a ThreadPool , which has a bunch of threads, that are available for executing any task when you need them. That way, you reduce the overhead of starting up and destroying the thread every time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM