Java Threading: How does implementing runnable work for threading

前端 未结 5 1171
Happy的楠姐
Happy的楠姐 2021-02-10 00:21

I understand that if you want to thread you can either extend thread or implement runnable to multithread in java. But why do you have to implement an interface for java to thre

5条回答
  •  心在旅途
    2021-02-10 01:14

    But why do you have to implement an interface for java to thread?

    You don't, as you said previously you can extend the Thread object and implement a public void run method. If you want a more organized and flexible (yes, flexible) approach you definitely want to use Runnable for an obvious reason: Code reusability.

    When I say organized, I want to say that it's easy to maintain a

    Runnable doSomething = new Runnable()
    {
        @Override
        public void run()
        {
            goAndDoSomethingReallyHeavyWork();
        }
    };
    

    and then reuse the same runnable for another thread, or the same thread in another moment (yes, you can actually re-use a Thread) than extend 2 or more threads into objects that you will use once.

    Whats the importances of the runnable interface that makes java threading work?

    The importance is that the Thread object will "know" that your Runnable has a method run and will execute it when it have to (and so stop, pause and other Thread actions).

    Does Java's interface extend from something?

    This question is worth my +1 to you. I would really like to know, but it seems it's a feature of the language and not a product of itself like every other object that extends the Object super class.

    I hope it helped. Cheers

提交回复
热议问题