001 Thread creation

I. Overview

In java, the Thread class describes the concept of thread, and creating a thread is to create a Thread. In order to divide the concept of concurrent tasks and concurrency itself, the Runnable interface is provided to separate the logical unit of threads.


 

2. Inherit Thread to create a thread 

    @Test
    public void extendsThread() {
        new Thread() {
            @Override
            public void run() {
                for(;;)
                    System.out.println("extends Thread ....");
            };
        }.start();
    }

  Above, we created a thread by inheriting Thread, and used the start() method to run the thread. Here, the start of the thread needs to call the start() method, and the reasons will be analyzed later.


 

3. Use Runnable to separate thread logical units  

    @Test
    public void implementsRunnable() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(;;)
                    System.out.println("implements Runnable ...");
            }
        }).start();
    }

  Above, we implemented a Runnable interface and passed it as a parameter to the Thread class. We will analyze this situation later.


 4. Thread class

  

We see that Thread itself implements the Runnable interface.

  

We see that the constructor of Thread can pass a Runable interface object.

  Summary: When the thread object starts, it will call the run() method. First, it will determine whether it has a target (the passed Runnable), and if it does not, it will execute its own run() method.

 

Guess you like

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