线程启动详解

本文详细介绍了Java中启动线程的start()方法和执行业务逻辑的run()方法的区别与联系。start()方法用于启动新线程并进行线程执行前的准备工作,包括设置上下文和等待CPU资源,而run()方法则包含线程的具体业务。调用start()后线程可能因调度延迟执行,且不允许重复调用。同时,分析了start()的源码和run()在不同线程创建方式下的执行情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、start()和run()

这两个方法是在开发中实现多线时,最常接触的方法,start()是线程启动的方法,run()是线程中具体要实现的业务逻辑,这两个方法有直接的联系,但又是两个完全不同的方法,start()用来启动一个新的线程,而启动的新的线程主题逻辑就是run()。这两个方法不能孤立存在,只有start()不产生任何现实意义,只有run()不会创建新的线程。

实例代码:

public class StartAndRunMethod {
    public static void main(String[] args){
        Runnable runnable = () -> {
            System.out.println(Thread.currentThread().getName());
        };
        /**
         * 直接调用run方法是直接通过主线程来执行的,
         * 这肯定是不符合我们的本意,我们是准备新建一个线程执行的;
         * */
        runnable.run();
        /**
         * 通过新建子线程进行执行的;
         * */
        new Thread(runnable).start();
    }
}

二、start()方法的作用:

1、启动新的线程:

start()通知jvm在空闲的情况下启动新线程,所以说启动一个新线程的本质就是请求jvm来运行我们的线程,对于这个线程何时可以运行,并不是由我们决定的,而是说线程调度器决定。所以start执行之后,子线程并不一定会运行,它可能稍后才会运行,可能很长时间都不被运行,比如遇到了饥饿的情况;

2、线程执行前的准备工作:子线程运行之前的准备工作,包含:让子线程处于就绪状态(已经设置了上下文,栈,线程状态,以及PC(寄存器)),处于等待CPU的状态;做完准备工作之后,我们的线程才能被jvm或操作系统进一步调度到执行状态,调度到执行状态,等待获取cpu资源,然后才能真正的进入到运行状态,执行run方法里面的那些代码。

3、不能重复start();重复调用start()会报java.lang.IllegalThreadStateException异常,因为在调用start()的时候会先判断Thread状态,也就是threadStatus 是否为0,如果不为0,也就是线程已经启动过了,就直接抛IllegalThreadStateException异常。

源码:

/* Java thread status for tools,
 * initialized to indicate thread 'not yet started'
 */

private volatile int threadStatus = 0;

从start()源码可以看出,线程的启动要经过:

1、检查新新线程状态,验证线程是否尚未启动(threadStatus是否为0 );

2、加入线程组;

3、调用start0()通知jvm启动线程;

/**
 * Causes this thread to begin execution; the Java Virtual Machine
 * calls the <code>run</code> method of this thread.
 * <p>
 * The result is that two threads are running concurrently: the
 * current thread (which returns from the call to the
 * <code>start</code> method) and the other thread (which executes its
 * <code>run</code> method).
 * <p>
 * It is never legal to start a thread more than once.
 * In particular, a thread may not be restarted once it has completed
 * execution.
 *
 * @exception  IllegalThreadStateException  if the thread was already
 *               started.
 * @see        #run()
 * @see        #stop()
 */
public synchronized void start() {
    /**
     * This method is not invoked for the main method thread or "system"
     * group threads created/set up by the VM. Any new functionality added
     * to this method in the future may have to also be added to the VM.
     *
     * A zero status value corresponds to state "NEW".
     */
    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    /* Notify the group that this thread is about to be started
     * so that it can be added to the group's list of threads
     * and the group's unstarted count can be decremented. */
    group.add(this);

    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            /* do nothing. If start0 threw a Throwable then
              it will be passed up the call stack */
        }
    }
}

实例代码:

/**
 * 描述: 测试如果两次执行start方法会怎么样
 *
 * **/
public class CantStartTwice {

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

三、Run()源码:

/* What will be run. */
private Runnable target;
/**
 * If this thread was constructed using a separate
 * <code>Runnable</code> run object, then that
 * <code>Runnable</code> object's <code>run</code> method is called;
 * otherwise, this method does nothing and returns.
 * <p>
 * Subclasses of <code>Thread</code> should override this method.
 *
 * @see     #start()
 * @see     #stop()
 * @see     #Thread(ThreadGroup, Runnable, String)
 */
@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

如果通过Runnable方法创建线程,将传入的对象赋值给target,调用Thread提供的run(),通过继承Thread实现,重写run(),执行子类重写的run();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值