• Thread的run方法和start方法


    thread调用start()方法,可以理解为,start()方法通知“线程规划器”此线程已经准备就绪,等待调用线程对象的run()方法。这个过程其实就是让系统安排一个时间来调用Thread中的run()方法,也就是使线程得到运行,启动线程,具有异步执行的效果。如果直接调用代码thread.run()方法,就不是异步执行了,而是同步,那么此线程对象并不交给“线程规划器”来进行处理,而是由main主线程来调用run()方法,也就是必须等run()方法中的代码执行完后才可以执行后面的代码。源代码如下:
    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 */
               }
           }
       }
    
       private native void start0();
    
       /**
        * 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();
           }
       }
    另外,还需要注意一下,执行start()方法的顺序不代表线程启动的顺序。
  • 相关阅读:
    [SpringCloud] Hystrix原理及应用
    Excel框设置下拉选项
    The program no longer exists.
    win10 指纹登录修改用户密码
    git 比较两个分支内容差异
    C++ 已知两个时间(年月日)求日期差
    SELECT INTO 和 INSERT INTO SELECT 两种表复制语句详解(SQL数据库和Oracle数据库的区别)
    SQL Server查询优化方法
    xshell连接ubuntu虚拟机的方法
    beyond compare添加Java反编译插件
  • 原文地址:https://www.cnblogs.com/ZoHy/p/12400682.html
Copyright © 2020-2023  润新知