Java 线程与 Pthreads
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5269535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Threads vs Pthreads
提问by Chander Shivdasani
I was asked this question in an interview today.
今天面试的时候被问到这个问题。
"When we create a thread with pthread_create()
(POSIX Threads), the thread starts on its own. Why do we need to explicitly call start()
in Java. What is the reason that Java doesnt start the thread when we create an instance of it."
“当我们使用pthread_create()
(POSIX Threads)创建线程时,线程会自行启动。为什么我们需要start()
在 Java 中显式调用。当我们创建它的实例时,Java 没有启动线程的原因是什么。”
I was blank and interviewer was short of time and eventually he couldn't explain the reason to me.
我很茫然,面试官时间很紧,最终他无法向我解释原因。
采纳答案by sbridges
In Java not starting the thread right away leads to a better API. You can set properties on the thread (daemon, priority) without having to set all the properties in the constructor.
在 Java 中,不立即启动线程会导致更好的 API。您可以在线程上设置属性(守护进程、优先级),而无需在构造函数中设置所有属性。
If the thread started right away, it would need a constructor,
如果线程立即启动,它将需要一个构造函数,
public Thread(Runnable target, String name, ThreadGroup threadGroup, int priority, boolean daemon, ContextClassLoader contextClassLoader, long stackSize)
To allow setting all these parameters before the thread started. The daemon property can't be set after the thread has started.
允许在线程启动之前设置所有这些参数。线程启动后无法设置守护进程属性。
I'm guessing that the POSIX API takes a struct with all the thread properties in the call to pthread_create()
, so it makes sense to start the thread right away.
我猜测 POSIX API 在对 的调用中采用具有所有线程属性的结构pthread_create()
,因此立即启动线程是有意义的。
回答by bestsss
The reasons are a lot. But I'll give you a few:
原因很多。但我会给你一些:
- The thread, itself, might start executing before returning the instance.
- The context classloader MUST be set properly before running the thread (look at the previous point)
- Extra configuration like priority should be set before starting the thread
- pthreads uses a pointer to the initialized structure(s), since the java.lang.Thread cannot be properly initialized in the end of the c-tor, see points above; straight call to the native
pthread_create
to actually execute the code makes no sense
- 线程本身可能会在返回实例之前开始执行。
- 在运行线程之前必须正确设置上下文类加载器(查看上一点)
- 在启动线程之前应该设置像优先级这样的额外配置
- pthreads 使用指向初始化结构的指针,因为 java.lang.Thread 无法在 c-tor 的末尾正确初始化,请参阅上面的要点;直接调用本机
pthread_create
来实际执行代码是没有意义的
I hope you get the idea.
我希望你明白。