Three ways to create threads and their pros and cons

How to create a thread:

First, inherit the thread class to create a thread

    1. Define a class to create a thread to inherit from the Thread class and override the run() method. The run() method is the task to be completed by the thread, which is called the execution body of the thread.

    2. Create an instance that inherits the Thread class, thus creating a thread object.

    3. The object calls the start() method to start the thread.

2. Implement the runable interface to create a thread

    1. Define a class that implements the runable interface and rewrite the run() method. Like the above example, the run() method is also the execution body of the thread.

    2. First create an entity that implements the runable class, and then use this entity as the target of the Thread class to create a thread object.

    3. Call the start() method of the thread object to start the thread.

3. Through Callable and Future

    1. Define a class that implements the Callable<> interface, and override the call() method, which is the execution body of the thread.

    2. Create an entity of the class whose call implements the interface, wrap the newly created entity with the FutureTask class, and then create a FutureTask entity.

    3. Use the FutureTask entity as the Thread target to create a thread object, and call the start() method to start the thread

    4. You can obtain the return value after the thread ends by calling the get() method in the FutureTask entity. The get() method will block the thread.


Comparison of the pros and cons of the three methods

1. Advantages of using runable and callable:

        A class just implements an interface and can also inherit from other parent classes.

        These two methods can allow multiple threads to share a target, so it is very suitable for multiple identical threads to process the same resource, thereby separating the CPU, code and data, forming a clearer model, which better reflects the object-oriented Thought.

Second, the disadvantages of using runable and callable:

        The programming is more complicated, and the thread.currThread() method must be used to obtain the current thread.

Third, the advantages of inheriting the Thread class:

        Programming is relatively simple, you can directly use this to get the currently executing thread

Fourth, the disadvantages of inheriting the Thread class:

        After inheriting the Thread class, you cannot inherit from other classes.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324727684&siteId=291194637