What will I learn?
This tutorial covers following topics:
- Multithreading
- Life cycle of threading
- creating threads
Requirements
- A laptop /PC with Mac OS/ Linux/ Wondows
- Preinstalled openjdk
- Preinstalled jvm
- Preinstalled Codeeditor
Difficulty
Intermediate, you must have good knowledge of basics of java programming to catch up this tutorial.
Tutorials Content
In the previous tutorial, we have learned about Multithreading In Python, defined multithreading and implemented in Python.
Now we will discuss multithreading in Java. Multithreading is the occurrence of multiple threads in a program, in which each thread acts as a single program and is different from each other
but uses same memory space, unlike different programs.
Life cycle of a thread
It is necessary to know the life cycle of the thread before we start multithreading in java. In a thread process, the thread may transit into different stages of its life cycle. The different
states of thread life cycle are as follows:
Newborn state: In this state the thread object is created and we are only allowed to do two operations i.e. scheduling the thread to run or kill the thread.
start() is used to schedule it for running and stop() to stop the thread.Runnable state: In this state, the thread will be executed as soon as the processor is available. If there are multiple threads in the queue to be executed than they are executed in First come - First serve approach.
Running state: In this state thread is being executed or processor has given it's time for that particular thread. While the thread is in running state we can be suspended by using
suspend() method and revived again by using resume(), we can make it pause using sleep(time) method which takes time as a compulsory argument and enters again into runnable
state as soon as time finishes.Also, we can make a thread to wait till the certain condition is met using wait() method and is scheduled to work again after the condition is met using notify().Blocked State: In this state thread is either suspended, sleeping or waiting, so it can't enter runnable and running state but it can be run again when certain requirements are met.
Dead state: In this state thread completed it's executing a process or is either killed by using stop().
Creating threads
In Java, threads are created as objects with method run() which gets called by respective thread object and is initiated by start().
We can create new threads by:
- Using a thread class
- Converting class to thread
Using a thread class
We will write a class which extends Thread class and implement the run() method to execute code as thread and call start() to initiate its execution.
Syntax
class ThreadName extends Thread
{
public void run()
{
.............
.............
{
}
Example:
We will look at an example of the thread which calculates area and perimeter of a square. We will create classes AreaSquare to calculate the area of the square and PeriSquare to calculate the
perimeter of square which extends Thread class. We use run() method to create thread objects and is initiated in ThreadTesting class by start() method.
// Creating class which extends Thread class
class AreaSquare extends Thread
{
// run method to create thread
public void run()
{
//defining array of lengths
int[] len = {5,6,7,8,9};
// defining loop to iterate array
for (int i = 0; i< len.length; i++ )
{
//calculating area
int area = len[i] * len[i];
//sleep method to pause execution of thread
try{
sleep(100);
}
catch(Exception e)
{
}
System.out.println("Area is " + area);
}
}
}
class PeriSquare extends Thread
{
public void run()
{
int[] len = {5,6,7,8,9};
for (int i = 0; i< len.length; i++ )
{
int perimeter = 4 * len[i];
try
{
sleep(100);
}
catch(Exception e)
{
}
System.out.println("Perimeter is " + perimeter);
}
}
}
class ThreadTesting
{
// main method
public static void main(String args[])
{
//initializing created thread
new AreaSquare().start();
new PeriSquare().start();
}
}
We have enclosed sleep() method inside try...catch blocks because it throws an exception which needs to be caught inorder to compile the program.
Now we have three threads in total, two threads we created by extending with Thread class and one as main program. All the threads are running independently and they may be executed
whenever processor can have time for them thus, they don't have special sequence of outputs.
AreaSquare as = new AreaSquare();
as.start()
This is equivalent to new AreaSquare().start()
where we created thread object and invoked run() method.
Output:
Perimeter is 24
Area is 49
Perimeter is 28
Area is 64
Perimeter is 32
Area is 81
Perimeter is 36
BUILD SUCCESSFUL (total time: 1 second)
What if we replace start() with run() in ThreadTesting class?
Our ThreadTesting class looks like:
class ThreadTesting
{
public static void main(String args[])
{
new AreaSquare().run();
new PeriSquare().run();
}
}
Output:
Area is 25
Area is 36
Area is 49
Area is 64
Area is 81
Perimeter is 20
Perimeter is 24
Perimeter is 28
Perimeter is 32
Perimeter is 36
BUILD SUCCESSFUL (total time: 1 second)
We can see that while calling run() method directly instead of start() then program executes sequentially and acts like single threaded program, this is because when we call run()
directly it will go into main thread and do not create separate thread for each object.
All above codes can be found on my GitHub link. Click here to download.
What's next?
In coming tutorials we will learn:
- Creating threads coverting class to threads
- Communication between threads
- Thread priority and more.
Posted on Utopian.io - Rewarding Open Source Contributors