Using the basic element of concurrency – thread
In this chapter, we will look at the java.lang.Thread
class and see what it can do for concurrency and program performance in general.
Getting ready
A Java application starts as the main thread (not counting system threads that support the process). It can then create other threads and let them run in parallel, sharing the same core via time-slicing or having a dedicated CPU for each thread. This can be done using the java.lang.Thread
 class that implements the Runnable
functional interface with only one abstract method, run()
.Â
There are two ways to create a new thread: creating a subclass of Thread
, or implementing the Runnable
interface and passing the object of the implementing class to the Thread
constructor. We can invoke the new thread by calling the start()
method of the Thread
class which, in turn, calls the run()
method that was implemented.
Then, we can either let the new thread run until its completion or pause it and let it continue...