in Core Java

Multithreading in Java – Introduction and Constructing Threads

Multithreading in Java – An Introduction

Multithreading in Java is one of the Important concepts in Core Java.  Most of the Beginners feel that this concept is more complex as well as confusing. In this article i have tried my best to give examples which can make the concepts simple.

Most of us have mobile phones – sorry, I mean everyone of us. Now, image a situation where we are speaking on phone and still.. we will be able to eat the food and going further, some SMART people can even watch TV while these two activities.

As humans, we are good at multitasking. Our brains are capable of shifting the priorities between these tasks and still be able to perform all of them together with ease.

In the same fashion, computers are designed to perform multiple operations in parallel so that different PROCESSES can execute in the system.  Just as we do, we are able to play the music in our computer and still be able to work on a document.

Multithreading in Java gives the ability to execute code by different threads to perform tasks in parallel or as a separate task without waiting for other to complete.

Computer games are the best examples of the Multithreading concept. The ability to make different objects act on a platform is enabled with the concept of Multithreading.

Anyone who played Road Rash – you can see that there are different bike compete with you which are driven by the computer – They are nothing but threads running in the game application.

Age of empires is also a good example of Multithreading.

We will see a good demonstration of Multithreading in Java.

Consider, we have a method which helps in downloading the files when you give the URL.  Now, when you want to download four files, you execute this method for four times  one after the other.  But what if the files are too large and you want all the downloads to happen in parallel?

We should be able to execute this code in parallel for four times right?. That’s what threads are for. Threads are nothing but the execution engines which execute the code independent of each other.

Now when four threads execute the code in parallel, we can download four files in parallel.  – Agreed?

You should understand a point here that there need not be four object for four threads.

Four threads can execute the code in a single object and even threads can create new Objects as well.

So, when it comes to thread it is important that you should be able to imagine how things are getting executing to be able to debug the issues related to multithreading environment. So, let me take a simple real life example to explain how threads can be imagined.

Lets consider, we have three electrical devices, a fan, lamp and an Iron box.

Now think that these devices are connected to ports which are connected with multiple lines. When you power any line, these devices will start working and even power in all the lines will also make them work.

So, you can consider the power through different wires to be threads and electrical devices as objects.

I hope, I was able to use this example to ignite your imagination to make this topic about threads simple.

Process and Threads:

Some of the people argue that process and threads are not different. But I think they are surely different.

You can think the process as an application running in your Operating system.

Consider a word application, It is a single process and when you type in word, a spell checker will keep working in the background to correct your words, this job can be considered as a thread.

So, you should understand that a process can have multiple threads in it.

So, a Java application running in a system is a process and can have multiple threads inside it.

Few more points to take you little deep into the threads concept and now,, we need to keep some points on top of mind.

First, as per definition – a thread is nothing but a thread of execution which executes the code. Then..

Every application has threads running in the background. Without threads, there will be NO application that will run.

When you use java class – your main method  starts getting executed – It means that the JVM is creating a thread to start executing the code in main method and we call this method as Main thread.

It is the Operating System which schedules the threads to be processed by the Processor. So the scheduling behavior is dependent on the OS. Again there is a Thread Scheduler inside JVM which coordinates with OS scheduler.

Remember that there is nothing that is guaranteed when it comes to the thread execution.  Do not bet that your thread will be executed at a time or so.. There is no guarantee..

Creating Threads:

Threads can be created using java.lang.Thread class.

So, when I say Thread t = new Thread(), this statement will create a Thread Object – Right, But remember it is only an object just like any other object you would create in Java. It cannot do anything. For now it is just a sitting duck.

Thread is the one which executes the code and puts things into action in the application.

Only when you say to start, It starts to execute the code. So, we need to invoke the start method on the thread object.

So, where does it start from? There should be a starting point right? Yes, it is the run() method..

So, Every thread object you create will have run() method.

But remember the run method in the Thread object has nothing in it which connects to our own code.

Because this is created by the Java  api developers and they really do not what super code we are going to write.

So, we need to override this run method to make it to invoke our objects, method etc,

For this, You should create your own thread type and extend it to the Thread class, then override the run method to put your own code to tell the thread to start the code execution from this point.

 So, let us see a simple Downloader example about creating threads.

Here, I have created a class called Downloader which extends thread.

This class has a constructor which gets the url from which the file has to be downloaded.

I have overridden the run method. The real download code is in the download method of FileDownloader class.

So, I have created the instance of it and I am passing the URL to this method.

Now to start downloading four files, I need four threads. So, I have created four Downloader objects.

To start downloading, I should invoke the start method. So, when the thread starts, each thread will have its corresponding FileDownloader object on which the download method will be executed.

All the four threads here run independent of each other. Any objects or values initialized by a thread will not be visible or available to other threads.

Using Runnable Interface instead of Thread:

If you look at the earlier code, you have seen that I have extended the Thread class. But this is inheritance here which means that Downloader is more advanced class than Thread class.

But in reality, the Downloader is no substitute in providing advanced methods. So, it is always recommended not inherit Thread class unless you are sure that you are going to write more sophisticated class than that is there in the Java.

So, the whole purpose of extending was to override the run method. For that Java api provides a Runnable interface which enforces to override run method.

Now , we need to create a Thread and tell where the target run is available for it to start executing. This we call as runnable target.

Thread class constructor accepts the Runnable type of object which understand that the run method is present in that object.

This way it helps to keep code simple and save the inheritance ladder.

After creating the Thread object and passing the runnable target, we should not forget to invoke the start method on it. If not, nothing is going to start.

Threads and its constructors:

There are three components which work with threads –

  1. Runnable target object in which the run method exists.
  2. Name of the thread which you can use the thread to identify in middle of the execution.
  3. And the last one is the Thread group. You can group your threads based on the activities they do.

Based on these three, The Thread class has constructors which accept different combinations of these parameters.

Threads Example:

Let us implement an example to create Threads. Consider a Race where two threads race to complete a 100 meters distance. Given below is the implementation of Race example:

A player is considered as Racer and the class implements Runnable Interface which indicates to Threads that its run method is implemented in Racer class.

This class makes the thread to iterate for 100 times and for each iteration, it checks if some one has won the race and if already a Thread won the race, then the other quits.

In the class, you can see that i have instantiated two thread objects and have passed the Target object which a Racer object.

Check how threads transit through different states: Thread States tutorial


Complete Video on Multithreading -Introduction and Thread creation

Multithreading – An Introduction java9s presentation download

Srinivas Reddy

Srinivas Reddy

An IT - Specialist with loads of experience in Java, J2ee platforms and loves to share his experience on technology with You...

More Posts - Website

Follow Me:

Related Posts

Srinivas Reddy
Written By:

An IT - Specialist with loads of experience in Java, J2ee platforms and loves to share his experience on technology with You...