Java线程与Pthreads [英] Java Threads vs Pthreads

查看:136
本文介绍了Java线程与Pthreads的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天在接受采访时被问到这个问题。

I was asked this question in an interview today.

当我们使用 pthread_create()(POSIX Threads)创建一个线程时,线程会自行启动。为什么我们需要在Java中显式调用 start()。当我们创建它的实例时,Java不会启动该线程的原因是什么。

"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."

我一片空白,面试官时间不够,最终他无法向我解释原因。

I was blank and interviewer was short of time and eventually he couldnt explain the reason to me.

推荐答案

在Java中,不立即启动线程会带来更好的API。您可以在线程(守护程序,优先级)上设置属性,而无需在构造函数中设置所有属性。

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.

如果线程立即启动,则需要构造函数,

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.

我猜测POSIX API在调用中采用了包含所有线程属性的结构 pthread_create(),所以立即启动线程是有意义的。

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.

这篇关于Java线程与Pthreads的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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