Java User
Java User

Reputation: 137

Java Thread: start() - How does it create a new thread?

I was wondering what goes inside a java thread start method that it's able to create a new thread?

Upvotes: 4

Views: 631

Answers (3)

Dolda2000
Dolda2000

Reputation: 25855

It's a native method, which means that it isn't implemented in Java itself, but in C++.

Exactly what it does, outside of JVM book-keeping, depends on the platform the JVM is running on; on Linux, it would run something like pthread_create(), or perhaps clone() directly. I don't know off-hand what the Windows alternatives are.

There are two main reasons why Java hides the underlying mechanism from you: Partly to make it easier for you to write Java programs without having to know the operating system they'll be running on, as an abstraction and a service to you; but partly also because being able to call such native functionality directly would break the security model that Java imposes, so it's also to make sure that no Java program can do anything untoward without explicit permissions.

In the end though, I'm not sure exactly why you're asking, so I'm not sure if I'm really answering your question.

Upvotes: 2

webuster
webuster

Reputation: 2510

Much like anything else in Java, creating a thread via the start() method involves the JVM. What the Java Virtual Machine does in general is to act as a mediator between your method calls and the underlying operating system. This ensures that the Java environment acts in (roughly) the same way regardless of the operating system (=> the famous Java portability). But what it does behind the curtain (i.e. in the internals of the JVM) differs and depends on the actual OS it's running on.

For example, creating a thread calls the pthread_create function (the POSIX thread call) on a Unix OS, or the CreateThread function on a Windows system (this is from the Win32 API). This is called by the Java Virtual Machine so you don't have to.

These functions are just examples. Depending on the particular JVM implementation (for differnent OS-es, mind you), the start() method might do other magic behind.

The principle, however, stays the same. The start() method calls something that your particular OS natively supports for creating threads.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201429

A specific answer will is impossible because it varies by platform (in the long ago there were Green threads and all was clear - they ran as user level threads). Since that time they've been replaced with Native threads, as an "optimization". That is, green threads were removed in favor of the idiomatic threading model of the native operating system. Regardless, native code will eventually invoke your programmed run method.

Upvotes: 1

Related Questions