• 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()方法的顺序不代表线程启动的顺序。
  • 相关阅读:
    Monkeyrunner学习
    js判断字符串是否包含指定的字符
    Asp.net网站后台代码不能访问-iis部署
    css分割线 文字居中的7种实现方式
    css倒三角的几种实现方式
    前端一键切图
    html中em和px
    js日期控件demo
    网页字体样式
    html特殊符号列表
  • 原文地址:https://www.cnblogs.com/ZoHy/p/12400682.html
Copyright © 2020-2023  润新知