【问题标题】:What happens when creating a Thread instance, Java创建 Thread 实例时会发生什么,Java
【发布时间】:2015-02-04 11:33:51
【问题描述】:

我对 Java 线程和 OS 线程有疑问,我阅读了 Java Threads vs PthreadsJava Threads vs OS Threads,但我没有找到答案。

在调用 start() 之前我考虑过,没有创建 OS 线程。

但是根据https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.State.html

一个尚未启动的线程处于NEW状态。

我错了还是java doc中定义的状态不仅仅是为了标记线程实例的状态?

我的问题是:

  • 当我们创建一个线程实例但在调用start()之前究竟发生了什么
  • 什么时候真正用 Java 创建操作系统线程

【问题讨论】:

    标签: java multithreading


    【解决方案1】:
    Thread thread = new Thread(){
        @Override
        public void run() {
            // code
        }
    }; 
    // at this point the thread is in NEW state, all you have a simple java object, 
    // no actual thread is created
    
    thread.start();
    // when start() is invoked, at some unspecified point in the near future 
    // the thread will go into RUNNABLE state, this means an actual thread will be created.  
    // That can happen before start() returns.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 2014-09-22
      • 1970-01-01
      • 2015-01-17
      • 2019-06-13
      相关资源
      最近更新 更多