创建Thread实例Java时会发生什么

时间:2014-12-06 09:58:24

标签: java multithreading

我对Java线程和操作系统线程有疑问,我读了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中定义的状态不仅仅是标记Thread实例的状态吗?

我的问题是:

  • 在我们创建Thread实例但在调用start()
  • 之前到底发生了什么
  • OS线程何时真正用Java创建

1 个答案:

答案 0 :(得分:2)

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.