Java Threading: How does implementing runnable work for threading

前端 未结 5 1172
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:08

    The only thing special about the Runnable interface is that it is what Thread takes in its constructor. It's just a plain-old interface.

    As with most interfaces, the point is that you're programming to a contract: you agree to put the code you want to run in the Runnable#run() implementation, and Thread agrees to run that code in another thread (when you create and start a Thread with it).

    It's Thread that actually "does" the multithreading (in that it interacts with the native system). An implementation of Runnable is just where you put the code that you want to tell a Thread to run.

    In fact, you can implement a Runnable and run it, without having it run in a separate thread:

    Runnable someCode = new Runnable() {
        public void run() {
           System.out.println("I'm a runnable");
        }
    };
    someCode.run();
    

    So Runnable itself doesn't have anything to do with multi-threading, it's just a standard interface to extend when encapsulating a block of code in an object.

提交回复
热议问题