Java Programming/Threads and Runnables

CPUs for any computer are designed to execute one task at any given time, yet we run multiple applications side-by-side and everything works in perfect congruence. It's not just because CPUs are extremely fast in performing calculations, it's because CPUs use a clever device of dividing their time amongst various tasks. Each application or task that is invoked on a computer gets associated with the CPU in the form of a process. A CPU therefore manages various processes, and jumps back and forth amongst each process giving it a fraction of its time and processing capability. This happens so fast that to a normal computer user it presents with the illusion of processes being run simultaneously. This capability of the CPU to divide its time amongst processes is called multitasking.

So, if we run a Java application on a computer, we are effectively creating a process with the CPU that gets a fraction of the CPU's time. In Java parlance, this main process gets called the daemon process or the daemon thread. But, Java goes one step further. It allows programmers to divide this daemon thread into several multiple threads which get executed simultaneously (much like a CPU) hence providing a Java application with a finer multitasking capability called multithreading.

In this section, we will take a look at what threads are and how multithreading is implemented within a Java program to make it appear congruent and effectively fast to respond.

Threads
In light of the above discussion, a thread is the smallest unit of processing that can be scheduled by an operating system. Therefore, using threads, a programmer can effectively create two or more tasks that run at the same time. The first call-to-action is to implement a set of tasks that a particular thread would execute. To do so, we require the creation of a  process.

Creating a Runnable process block
A  process block is a simple class that implements a   method. Within the  method is the actual task that needs to be executed by a running thread. By implementing a class with the interface, we ensure that the class holds a   method. Consider the following program:

In the above code, we create a class called  and implement the   interface to ensure that we have a   method in the class declaration.

We then declare the rest of the logic for the class. For the constructor, we take a  parameter that would serve as the name of the class. Then, we initialize the class member variable  with a random number between   and. To ensure the initialization of a random number, we use the  class in the   package.

The actual task that would be executed per this runnable block is presented within the  method. To keep safe from exceptions occurring because of the concurrent programming, we wrap the code within this method with a  block. The executing task actually consists of just three statements. The first outputs the provided name for the Runnable process, and the last reports that the thread has executed. Perhaps the most intriguing part of the code is the second statement:.

This statement allows the thread executing the current runnable block to halt its execution for the given amount of time. This time is presented in milliseconds. But for our convenience, this time would be the random number generated in the constructor and can be anywhere between  and   milliseconds. We will explore this in a later section. Creating a  process block is just the beginning. No code is actually executed. To do so, we would require the creation of threads that would then individually execute this task.

Creating threads
Once we have a  process block, we can create various threads that can then execute the logic encased within such blocks. Multithreading capabilities in Java are utilized and manipulated using the class. A  object therefore holds all the necessary logic and devices to create truly multithreaded programs. Consider the following program:

Creating threads is as simple as the above program suggests. You just have to create an object of the  class and pass a reference to a   process object. In the case above, we present the  constructor with the class object for the   class that we created in code listing 1. But for each object, we give a different name (i.e.,  and , etc.) to differentiate between the three   objects. The above example only declares  objects and hasn't yet started them for execution.

Starting threads
Now, that we know how to effectively create a  process block and a   object that executes it, we need to understand how to start the created   objects. This couldn't be simpler. For this process, we will be calling the  method on the   objects and voilà, our threads will begin executing their individual process tasks.

The above code will start all three declared threads. This way, all three threads will begin their execution one-by-one. However, this being concurrent programming and us having declared random times for the halting of the execution, the outputs for every one of us would differ. Following is the output we received when we executed the above program.

It should be noted that the execution of the  didn't occur in the desired order. Instead of the order – –, the threads executed in the order of  – –. The order in which the threads are executed is completely dependent on the operating system and may change for every execution of the program, thus making output of multithreaded application difficult to predict and control. Some people suggest that this is the major reason that adds to the complexity of multithreaded programming and its debugging. However, it should be observed that once the threads were put to sleep using the  function, the execution intervals and order can be predicted quite capably. The thread with the least amount of sleeping time was   with   milliseconds of sleep hence it got called first. Then  was called and finally   was called.

Manipulating threads
It can be said that the execution order of the threads was manipulated to some degree using the  method. The  class has such static methods that can arguably affect the execution order and manipulation of threads. Below are some useful static methods in the  class. These methods when called will only affect the currently running threads.

Synchronization
Given below is an example of creating and running multiple threads that behave in a synchronous manner such that when one thread is using a particular resource, the others wait until the resource has been released. We will talk more about this in later sections.

Where are threads used?
Threads are used intensively in applications that require a considerable amount of CPU usage. For operations that are time-consuming and intensive, it is usually advised to use threads. An example of such an application would be a typical video game. At any given time, a video game involves various characters, objects in the surroundings and other such nuances that needs to be dealt with simultaneously. Dealing with each element or object within the game requires a fair amount of threads to monitor every object.

For example, take this screen-shot of a role-playing strategy game on the right. Here the game visuals depict various in-game characters moving about on the screen. Now imagine processing the movements, direction and behaviors of each of the characters visible on screen. It would certainly take a lot of time moving each character one-by-one if this were to be done one task after another. However if fundamentals of multi-threading are employed, each character would move in a synchronous manner with respect to others.

Threads are not only used heavily in video games, their use is common in everything from simple browser applications to complex operating systems and networking applications. Today it often goes beyond the simple preference of the developer but into the need to maximize the usefulness of contemporaneous hardware that is predicated in heavy multitasking.