Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Threads vs Pthreads

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

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

like image 981
Chander Shivdasani Avatar asked Mar 11 '11 06:03

Chander Shivdasani


People also ask

Does Java use pthreads?

Yes, HotSpot JVM (i.e. Oracle JDK and OpenJDK) uses pthreads on Linux and on Mac OS X.

Are pthreads OS threads?

POSIX Threads are commonly known as PThreads. It is an execution model that exists independently from a language and a parallel execution model. It allows a program to control multiple different workflows that overlap in time.

Are pthreads obsolete?

pthread is outdated since availability of C11 which introduced standard threading in C. The header files is <threads. h> with functions like thrd_create . The standard functions for threading, conditions, and signalling, provide guarantees that pthreads cannot.


1 Answers

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.

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.

like image 83
sbridges Avatar answered Sep 20 '22 07:09

sbridges