多线程核心2:多线程启动方式

start()与run()启动

public class StartAndRunMethod {
    
    
    public static void main(String[] args) {
    
    
        Runnable runnable = () -> {
    
    
            System.out.println(Thread.currentThread().getName());
        };

        runnable.run();

        new Thread(runnable).start();
    }
}

-------------------
运行结果是:
main
Thread-0
  • main线程调用new Thread(runnable).start();去创建Thread-0线程,并且不是一调用start就会创建新线程,而是等待CPU有空闲的时候采取创建新线程

  • 使用Runnable对象调用run()方法,就是普通的方法调用,是在main线程里执行;而使用start()方法启动线程才是真正启动多线程,下面是Thread类中的start()方法:

    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".
             */
        	
        	//启动新线程检查线程状态是否为0
            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方法
                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();
    }
}

答案是不能,通过看Thread类的start()方法知道在创建线程是会检查线程状态threadStatus,如果不是新的线程就会抛出异常java.lang.IllegalThreadStateException

猜你喜欢

转载自blog.csdn.net/weixin_44863537/article/details/112060269