创建线程实例Java时会发生什么 [英] What happens when creating a Thread instance, Java

查看:180
本文介绍了创建线程实例Java时会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java线程和OS线程有疑问,我阅读了 Java线程与Pthreads Java线程与OS线程,但我没有找到困惑的答案.

I have a questions about Java thread and OS thread, and I read Java Threads vs Pthreads and Java Threads vs OS Threads but I does not find an answer to my confusions.

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

I had considered before we call start(), no OS thread is created .

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

尚未启动的线程处于NEW状态.

我是错误的还是在Java doc中定义的状态不仅是为了标记Thread实例的状态?

Am I wrong or the states defined at java doc are not only to mark the state of Thread instance?

我的问题是:

  • 当我们创建Thread实例时但在调用start()
  • 之前会发生什么情况
  • 什么时候真正用Java创建了OS线程
  • what exactly happens when we create a Thread instance but before calling start()
  • when does a OS thread really created in Java

推荐答案

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.

这篇关于创建线程实例Java时会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆