Multithreading in Java With Examples
Multithreading in Java With Examples
Before we talk about multithreading, lets discuss threads. A thread is a lightweight smallest part of a process that can run concurrently with the other
parts(other threads) of the same process. Threads are independent because they
all have separate path of execution thats the reason if an exception occurs in one
thread, it doesnt affect the execution of other threads. All threads of a process
share the common memory. The process of executing multiple threads
simultaneously is known as multithreading.
Lets summarize the discussion in points:
1. The main purpose of multithreading is to provide simultaneous execution of two
or more parts of a program to maximum utilize the CPU time. A multithreaded
program contains two or more parts that can run concurrently. Each such part of a
program called thread.
2. Threads are lightweight sub-processes, they share the common memory space.
In Multithreaded environment, programs that are benefited from multithreading,
utilize the maximum CPU time so that the idle time can be kept to minimum.
3. A thread can be in one of the following states:
NEW A thread that has not yet started is in this state.
RUNNABLE A thread executing in the Java virtual machine is in this state.
BLOCKED A thread that is blocked waiting for a monitor lock is in this state.
WAITING A thread that is waiting indefinitely for another thread to perform a
particular action is in this state.
TIMED_WAITING A thread that is waiting for another thread to perform an action
for up to a specified waiting time is in this state.
TERMINATED A thread that has exited is in this state.
A thread can be in only one state at a given point in time.
Read more about thread states at this link: Life cycle of threads
Multitasking vs Multithreading vs
Multiprocessing vs parallel processing
If you are new to java you may get confused among these terms as they are used
quite frequently when we discuss multithreading. Lets talk about them in brief.
Multitasking: Ability to execute more than one task at the same time is known as
multitasking.
getName():
getPriority():
isAlive():
join():
run():
sleep():
start():
Output:
Example 2:
class Count extends Thread
{
Count()
{
super("my extending thread");
System.out.println("my thread created" + this);
start();
}
public void run()
{
try
{
for (int i=0 ;i<10;i++)
{
System.out.println("Printing the count " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("my thread interrupted");
}
System.out.println("My thread run is over" );
}
}
class ExtendingExample
{
public static void main(String args[])
{
Count cnt = new Count();
try
{
while(cnt.isAlive())
{
System.out.println("Main thread will be alive till the child thread is live");
Thread.sleep(1500);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread's run is over" );
}
}
Output:
my thread createdThread[my runnable thread,5,main]
Main thread will be alive till the child thread is live
Printing the count 0
Printing the count 1
Main thread will be alive till the child thread is live
Printing the count 2
Main thread will be alive till the child thread is live
Printing the count 3
Output:
My thread is in running state.
Example Program 2:
Observe the output of this program and try to understand what is happening in this
program. If you have understood the usage of each thread method then you should
not face any issue, understanding this example.
class Count implements Runnable
{
Thread mythread ;
Count()
{
mythread = new Thread(this, "my runnable thread");
System.out.println("my thread created" + mythread);
mythread.start();
}
public void run()
{
try
{
for (int i=0 ;i<10;i++)
{
System.out.println("Printing the count " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("my thread interrupted");
}
System.out.println("mythread run is over" );
}
}
class RunnableExample
{
public static void main(String args[])
{
Count cnt = new Count();
try
{
while(cnt.mythread.isAlive())
{
System.out.println("Main thread will be alive till the child thread is live");
Thread.sleep(1500);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread run is over" );
}
}
Output:
Thread priorities
Thread priorities are the integers which decide how one thread should be
treated with respect to the others.
Thread priority decides when to switch from one running thread to another,
process is called context switching
A thread can voluntarily release control and the highest priority thread that
is ready to run is given the CPU.
To set the priority of the thread setPriority() method is used which is a method
of the class Thread Class.
In all the practical situations main thread should finish last else other
threads which have spawned from the main thread will also finish.
To know whether the thread has finished we can call isAlive() on the thread
which returns true if the thread is not finished.
Another way to achieve this by using join() method, this method when called
from the parent thread makes parent thread wait till child thread
terminates.
Synchronization
When two or more threads need access to a shared resource there should be
some way that the resource will be used only by one resource at a time. The
process to achieve this is called synchronization.
Inter-thread Communication
We have few methods through which java threads can communicate with each
other. These methods are wait(), notify(), notifyAll(). All these methods can only be
called from within a synchronized method.
1) To understand synchronization java has a concept of monitor. Monitor can be
thought of as a box which can hold only one thread. Once a thread enters the
monitor all the other threads have to wait until that thread exits the monitor.
2) wait() tells the calling thread to give up the monitor and go to sleep until some
other thread enters the same monitor and calls notify().
3) notify() wakes up the first thread that called wait() on the same object.
notifyAll() wakes up all the threads that called wait() on the same object. The
highest priority thread will run first.