Three ways to create a thread

There are three ways to create a thread:

①Inheriting the Thread class (the thread class in the true sense) is the implementation of the Runnable interface.

② Implement the Runnable interface and rewrite the run method inside.

③ Use the Executor framework to create a thread pool. The Executor framework is an implementation of the thread pool provided in juc

This article will give examples of the first two:

(1) Inheriting the Thread class

public class Test1 extends Thread {

    public void run(){
        System.out.println("I am a thread that inherits Thread");
    }

    public static void main(String[] args) {
        Test1 test1 = new Test1();
        test1.start();
    }

}

(2) Implement the Runnable interface

public class Test2 implements Runnable{
    @Override
    public void run() {
        System.out.println("I am a thread implementing the Runnable interface");
    }

    public static void main(String[] args) {
        Test2 test2 = new Test2();
        new Thread(test2).start();
    }
}

Under normal circumstances, the second one is used more, and the benefits are as follows:

1> Avoid multiple inheritance of classes. Classes can only inherit from a single class, but can implement multiple interfaces.

2> It is suitable for resource sharing. The class that implements the Runnable interface needs to be wrapped with the Thread class again before calling the start method. (Three Thread objects wrap a class object to achieve resource sharing).

There is another way to inherit the Thread class and implement the Runnable interface, which is an anonymous class, see the link

Anonymous class creation thread: https://blog.csdn.net/qq_39411607/article/details/79931502

Guess you like

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