J2EEOnline J2EE 






Java Concepts  «Prev  Next»
Lesson 4Creating and starting a new thread
ObjectiveBe able to create and start a new thread

Creating a new thread in Java

This lesson discusses how to create and start a new thread and identify the method invoked when a thread runs.
The Java platform has had support for multithreaded programming from the very first version. The platform exposes the ability to create new threads of execution to the developer.

lambda expression

Following example creates a new thread using a lamba expression.
Thread t = new Thread(() -> {System.out.println("Hello Thread");});
t.start();
This small piece of code creates and starts a new thread, which executes the body of the lambda expression and then executes.
For programmers coming from older versions of Java, the lambda is effectively being converted to an instance of the Runnable interface before being passed to the Thread constructor. The threading mechanism allows new threads to execute concurrently with the original application thread and the threads that the JVM itself starts up for various purposes.

Runtime-managed concurrency

For most implementations of the Java platform, application threads have their access to the CPU controlled by the operating system scheduler which is a built-in part of the OS that is responsible for managing timeslices of processor time (and that will not allow an application thread to exceed its allocated time).
In more recent versions of Java, an increasing trend towards runtime-managed concurrency has appeared. This is the idea that for many purposes explicit management and forget capabilities, whereby the program specifies what needs to be done, but the low-level details of how this is to be accomplished are left to the runtime. This viewpoint can be seen in the concurrency toolkit contained in java.util.concurrent.


Starting and stopping a thread
Simply creating the thread is not enough.
It is like clearing a space on the floor for a toy top but never playing with it. You must also start it spinning, by invoking its start() method:
t.start();
This method creates the system resources required to run a new thread and makes Java call the thread's run() method.
The thread will live as long as the run() method does not exit.
public void run()
If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
Subclasses of Thread should override this method. At a minimum, you must override run(), so that your thread will have a real purpose in life.
In the next lesson, we will apply this information on threads in an exercise.