UNIT-V
MultiThreading
Main thread in Java
Que:
1. Define Thread in Java.
2. Define thread. State two ways to create a thread.
3. Explain ‘Extending Thread class’ in Java.
4. What is Thread? List different methods used to create Thread. Explain Thread life cycle.
Ans:
Java provides built-in support for multithreaded programming. A multi-threaded program
contains two or more thread that can run concurrently.
Definition:
Thread can be called lightweight process. Thread requires less resources to create and
exists in the process, thread shares the process resources.
When a Java program starts up, one thread begins running immediately. This is usually
called the main thread of our program, because it is the one that is executed when our
program begins.
Properties :
It is the thread from which other “child” threads will be spawned.
Often, it must be the last thread to finish execution because it performs various shutdown
actions.
Creating Thread
We can create thread by creating object of type thread.
Java defines two ways to create thread.
1.Implementing Runnable Interface
2.Extending Thread Class
1) Implementing Runnable Interface
The easiest way to create a thread is to create a class that implements
the Runnable interface.
To implement Runnable interface, a class need only implement a single method called
run( ), which is declared like this:
public void run( );
Inside run( ), we will define the code that constitutes the new thread.
To execute the run() method by a thread, pass an instance of ABC to a Thread in its
constructor.
Page 1 of 11
Example:
class ABC implements Runnable
{
public void run()
{
System.out.println("ABC running");
}
}
class ThreadRunnable
{
Public static void main(String args[])
{
ABC ob1=new ABC();
Thread t1 = new Thread(ob1);
t1.start();
}
}
When the thread is started it will call the run() method of the MyClass instance instead of
executing its own run() method.
The above example would print out the text “ABC running“.
2.Extending Thread Class
In this method, create a new class that extends Thread.
Then override the run() method and create an instance of that class.
After that, call start() method to execute run() method.
Example:
class ABC extends Thread
{
public void run()
{
System.out.println("ABC running");
}
}
class ThreadExtend
{
public static void main(String args[])
Page 2 of 11
{
ABC t1 = new ABC();
t1.start();
}
}
When the run() method executes it will print out the text “ABC running“.
Multiple Threads
Our program can affect as many threads as it needs. Let’s see how we can create multiple
threads.
1.Multiple thread by Runnable Interface
class ABC implements Runnable
{
String name;
ABC(String str)
{
name=str;
Thread t1=new Thread(this);
t1.start();
}
public void run()
{
try
{
for(int i=0;i<5;i++)
{
System.out.println(name + " is Running: "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Thread is Interrupted"+e);
}
}
}
class multiThread
{
Page 3 of 11
public static void main(String args[])
{
ABC ob1=new ABC("Thread1");
ABC ob2=new ABC("Thread2");
2) Multiple Thread By extending Thread class
class ABC extends Thread
{
String name;
ABC(String str)
{
name=str;
start();
public void run()
{
try
{
for(int i=0;i<5;i++)
{
System.out.println(name + " is Running: "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Thread is Interrupted"+e);
}
}
}
class multiThread
{
public static void main(String args[])
{
ABC ob1=new ABC("Thread1");
Page 4 of 11
ABC ob2=new ABC("Thread2");
}
}
Life Cycle of Thread
Que:
1. Explain life cycle of a thread.
2. Explain life cycle of thread in Java.
3. Describe the complete life cycle of a thread.
Ans:
Following diagram shows Life Cycle of Thread.
New:
o The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
Runnable:
o The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
Running:
o The thread is in running state if the thread scheduler has selected it.
Waiting:
o Sometimes a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state
only when another thread signals the waiting thread to continue executing.
Terminated:
o A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
Thread Priority
Que:
Page 5 of 11
1. Explain thread priorities with suitable example.
2. List different thread priorities.
3. How do we set priorities for thread?
Ans:
In a Multi threading environment, thread scheduler assigns processor to a thread based on
priority of thread.
Whenever we create a thread in Java, it always has some priority assigned to it.
Priority can either be given by JVM while creating the thread or it can be given by programmer
explicitly.
Accepted value of priority for a thread is in range of 1 to 10.
There are 3 static variables defined in Thread class for priority.
1. public static int MIN_PRIORITY: This is minimum priority that a thread can have. Value for
this is 1.
2. public static int NORM_PRIORITY: This is default priority of a thread if do not explicitly
define it. Value for this is 5.
3. public static int MAX_PRIORITY: This is maximum priority of a thread. Value for this is 10.
Get and Set Thread Priority:
1. public final int getPriority():
o java.lang.Thread.getPriority() method returns priority of given thread.
2. public final void setPriority(int newPriority):
o java.lang.Thread.setPriority() method changes the priority of thread to the value
newPriority.
o This method throws IllegalArgumentException if value of parameter newPriority
goes beyond minimum(1) and maximum(10) limit.
Examples of getPriority() and setPriority
class ABC extends Thread
{
public void run()
{
System.out.println("ABC running");
}
}
class ThreadExtend
{
public static void main(String args[])
{
ABC t1 = new ABC();
t1.start();
System.out.println(t1.getPriority());
Page 6 of 11
t1.setPriority(2);
System.out.println(t1.getPriority());
System.out.println(Thread.currentThread().getName());
}
Synchronization
Que:
1. Explain Synchronization in Thread.
2. What is Synchronization? When do we use it?
3. Explain thread synchronization.
Ans:
When two or more threads need access to a shared resource,they need some way to
ensure that the resource will be used by only one thread at a time. The by which this is
achieved is called Synchronization.
There are two way to achieve synchronizarion
1) Using Synchronized Methods
2) Using Synchronized block
1.Using Synchronized Methods
To restrict to access of same method to only one thread at a time,we simply need to precede
method definition with the keyword synchronized.
Example:
class XYZ
{
synchronized public void display(String name)
{
try
{
for(int i=0;i<5;i++)
{
System.out.println(name+ " is Running: "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
Page 7 of 11
{
System.out.println("Thread is Interrupted"+e);
}
}
}
class ABC extends Thread
{
String name;
XYZ syob1;
ABC(XYZ ob1,String str)
{
syob1=ob1;
name=str;
start();
public void run()
{
syob1.display(name);
}
}
class SyncMethodThread
{
public static void main(String args[])
{
XYZ syob1=new XYZ();
ABC ob1=new ABC(syob1,"Thread1");
ABC ob2=new ABC(syob1,"Thread2");
}
}
2) Using synchronized block
General form of synchronized statement
Synchronized(object)
{
//statements to be Synchronized
}
Page 8 of 11
Object is a reference to the object being synchronized.
Example:
class XYZ
{
public void display(String name)
{
try
{
for(int i=0;i<5;i++)
{
System.out.println(name+ " is Running: "+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Thread is Interrupted"+e);
}
}
}
class ABC extends Thread
{
String name;
XYZ syob1;
ABC(XYZ ob1,String str)
{
syob1=ob1;
name=str;
start();
public void run()
{
synchronized(syob1)
{
syob1.display(name);
Page 9 of 11
}
}
}
class SyncThread
{
public static void main(String args[])
{
XYZ syob1=new XYZ();
ABC ob1=new ABC(syob1,"Thread1");
ABC ob2=new ABC(syob1,"Thread2");
}
}
Methods of thread class
Method Description
setName() to give thread a name
getName() return thread's name
getPriority() return thread's priority
isAlive() checks if thread is still running or not
join() Wait for a thread to end
run() Entry point for a thread
sleep() suspend thread for a specified time
start() start a thread by calling run() method
Page 10 of 11
\
Page 11 of 11