线程的启动

1.正确和错误的实现方式

/**
 * 描述:对比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();
    }
}

代码运行结果如下所示,由此可知,启动线程的正确方式是调用start方法。

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

2.start方法的含义

  • 启动新线程。请求JVM开启子线程的任务,这里需要注意的是,执行start方法后,线程任务并不一定会被立刻执行,何时被执行取决于JVM的调度。
  • 准备工作。使线程处于就绪状态,准备除CPU执行权以外的所有资源,如内存和程序运行时的上下文环境。
  • 不能重复执行start方法。执行start方法前,需要检查线程的状态,如果不是0,则会抛出线程状态异常IllegalThreadStateException。

3.start方法源码

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();
}

猜你喜欢

转载自blog.csdn.net/Jgx1214/article/details/108248166