About the execution method of Thread's start and run methods

Today, I suddenly thought of starting a sub-thread in the main thread and wondering whether it can be automatically destroyed after the sub-thread is executed. With the problem, I began to think about coding. In the coding process, Runnable and Thead were used in two different ways. , let's take a look at the first Runnable method.

  1. Runnable way
class RunnableTest implements Runnable {

    @Override
    public void run() {
        System.out.println("我是新启动的Runnable!");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

In this method, first let the child thread sleep for 2 seconds (for observing the changes of the thread while continuously viewing all the current threads in the main thread), the main thread is called as follows:

public class ThreadDemo {
    public static void main(String[] arg) throws InterruptedException {
        RunnableTest().run();
        while (true){
            Thread[] threads = findAllThreads();
            for(Thread t : threads){
                System.out.println(t.getId()+":"+t.getName());
            }
            Thread.sleep(1000);
        }
    }

    /**
     * 用于获取当前JVM中所有的线程
     * @return
     */
    public static Thread[] findAllThreads() {
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        ThreadGroup topGroup = group;
        // 遍历线程组树,获取根线程组
        while (group != null) {
            topGroup = group;
            group = group.getParent();
        }
        // 激活的线程数加倍
        int estimatedSize = topGroup.activeCount() * 2;
        Thread[] slacks = new Thread[estimatedSize];
        //获取根线程组的所有线程
        int actualSize = topGroup.enumerate(slacks);
        Thread[] threads = new Thread[actualSize];
        System.arraycopy(slacks, 0, threads, 0, actualSize);
        return threads;
    }
}

A problem was found after running. After calling the RunnableTest().run() method, it was found that the main thread was blocked, and the subsequent while loop body was not executed immediately. As a result, the sleep in the child thread was executed first, and after the sleep was over, The subsequent code of the main thread is executed. At this time, there is no shadow of the child thread in all the output threads, as follows:
write picture description here
There are only some system threads, but in the description, after the execution of the child thread is finished, it is immediately released, but the problem comes, the original I thought that the call of the child thread is asynchronous and will not block the main thread, but the effect here is blocking, and it is a bit unclear for a while. So, well, let's use the Thread method to see the effect.
2. Thread method

class ThreadTest extends Thread{
    @Override
    public void run() {
        System.out.println("我是新启动的Thread!");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Call new ThreadTest().start() in the main thread; at this time, it is found that after the call, the subsequent code in the main thread is executed immediately, and the main thread is not blocked, and the child is seen in the output of the thread situation. The shadow of the thread, and after the sleep of the child thread is over, the child thread is destroyed. The running result is as follows:
write picture description here
It can be seen that the shadow of the child thread can be seen at 1 and 2. At 3, because the sleep of the child thread ends, it is destroyed. , so there are no child threads. It can also be explained that the sub-thread is called in the main thread, and the sub-thread will be destroyed immediately after the execution ends. But the question is, why does the method of using Runnable.run() block the main thread, but the method of Thread.start() does not block? Below is a detailed discussion.


With the above questions, after replacing new ThreadTest().start(); with new ThreadTest().run();, the same main thread is blocked. It turns out that whether it is through Runnable.run() or Thread.run( ) operation is actually a call of a common class method. Of course, it is called sequentially. When Thread.start() is used, the specific execution of the child thread is determined by the system. The asynchronous execution does not block the main thread. At this point, doubts have appeared in the dark, haha, the discovery of the problem to the solution of the doubts, all the usual details are so-so, it is purely mediocre!

Guess you like

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