1. java线程如何启动

java线程启动是调用start()而非run()方法;
run()方法直接调用是方法调用,并不是线程在调用;
start()方法调用后也不是马上就会执行线程, 要看JVM如何调度和协调资源,适当时机才会调用线程.

2. java线程start()调用两次会如何?

// 源码地址: openjdk/src/hotspot/share/runtime/thread.cpp
// 
void Thread::start(Thread* thread) {
  // Start is different from resume in that its safety is guaranteed by context or
  // being called from a Java method synchronized on the Thread object.
  if (thread->is_Java_thread()) {
    // Initialize the thread state to RUNNABLE before starting this thread.
    // Can not set it after the thread started because we do not know the
    // exact thread state at that time. It could be in MONITOR_WAIT or
    // in SLEEPING or some other state.
    java_lang_Thread::set_thread_status(JavaThread::cast(thread)->threadObj(),
                                        JavaThreadStatus::RUNNABLE);
  }
  os::start_thread(thread);
}

3. 线程执行完成以后, 可以重新启动吗?

不能,线程的生命周期完成后,就不能重新开始.

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
not finished ...

丰木
322 声望19 粉丝

遇见超乎想象的自己!


引用和评论

0 条评论