Thread start

1. The right and wrong way to achieve

/**
 * 描述:对比start和run两种启动线程的方式。
 */
public class ThreadRunAndStart implements Runnable{
    
    
    @Override
    public void run() {
    
    
        System.out.println("当前线程名:" + Thread.currentThread().getName());
    }
    
    public static void main(String[] args) {
    
    
        ThreadRunAndStart threadRunAndStart = new ThreadRunAndStart();
        threadRunAndStart.run();

        Thread thread = new Thread(threadRunAndStart);
        thread.start();
    }
}

The results of the code execution are shown below, which shows that the correct way to start a thread is to call the start method.

当前线程名:main
当前线程名:Thread-0

2. The meaning of the start method

  • Start a new thread. Request the JVM to start the task of the child thread. It should be noted here that after the start method is executed, the thread task may not be executed immediately, and when it is executed depends on the JVM's scheduling.
  • Ready to work. Make the thread in a ready state, prepare all resources except CPU execution rights, such as memory and the context of the program runtime.
  • The start method cannot be executed repeatedly. Before executing the start method, you need to check the state of the thread. If it is not 0, an IllegalThreadStateException will be thrown.

3.start method source code

public class Thread implements Runnable {
    
    
	public synchronized void start() {
    
    
		//1.启动新线程前检查线程状态
        if (threadStatus != 0)
            throw new IllegalThreadStateException();
        //2.加入线程组
        group.add(this);
        boolean started = false;
        try {
    
    
        	//3.调用start0方法
            start0();
            started = true;
        } finally {
    
    
            try {
    
    
                if (!started) {
    
    
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
    
    
              
            }
        }
    }
	
	//调用本地方法启动线程
	private native void start0();
}

Guess you like

Origin blog.csdn.net/Jgx1214/article/details/108248166