Professional Documents
Culture Documents
Multi-threading in Java
INTRODUCTION
What is a Thread in Java?
• A thread in Java is the direction or path that is taken while a program is being
executed.
• Generally, all the programs have at least one thread, known as the main thread
main thread is provided by the JVM at the starting of the program’s execution.
• A thread enables multiple operations to take place within a single method.
• Each thread in the program often has its own program counter, stack, and local
variable.
Creating a Thread in Java
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
We can directly use the Thread class to spawn new threads using the constructors defined above. // the start() method moves the thread to the active state
FileName: MyThread1.java t.start();
// getting the thread name by invoking the getName() method
String str = t.getName();
System.out.println(str);
}
}
Commonly used Constructors of Thread
class:
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r,String name)
Those constructors Allocates a new Thread object.
Commonly used methods of Thread class
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the
run() method on the thread.
public void sleep(long miliseconds): Causes the currently executing
thread to sleep (temporarily cease execution) for the specified number of
milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
public int getPriority(): returns the priority of the thread.
Con…
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently
executing thread.
public int getId(): returns the id of the thread.
public Thread.State getState(): returns the state of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
Con…
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or user
thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been interrupted.
public static boolean interrupted(): tests if the current thread has been
interrupted.
Lifecycle of a Thread in Java
he Life Cycle of a Thread in Java refers to the state transformations of a
thread that begins with its birth and ends with its death.
When a thread instance is generated and executed by calling the start()
method of the Thread class, the thread enters the runnable state.
When the sleep() or wait() methods of the Thread class are called, the thread
enters a non-runnable mode.
Thread returns from non-runnable state to runnable state and starts statement
execution.
The thread dies when it exits the run() process.
In Java, these thread state transformations are referred to as the Thread life
cycle.
Con…
There are basically 4 stages in the lifecycle of a thread, as given
below:
1. New
2. Runnable
3. Running
4. Blocked (Non-runnable state)
5. Dead
Con…
New State
• As we use the Thread class to construct a thread entity, the thread is born and is
defined as being in the New state.
• That is, when a thread is created, it enters a new state, but the start() method on the
instance has not yet been invoked.
Runnable State
• A thread in the runnable state is prepared to execute the code.
• When a new thread's start() function is called, it enters a runnable state.
• In the runnable environment, the thread is ready for execution and is awaiting the
processor's availability (CPU time).
• That is, the thread has entered the queue (line) of threads waiting for execution.
Con…
Running State
• Running implies that the processor (CPU) has assigned a time slot to the thread for execution.
• When a thread from the runnable state is chosen for execution by the thread scheduler, it joins the running
state.
• In the running state, the processor allots time to the thread for execution and runs its run procedure.
• This is the state in which the thread directly executes its operations.
• Only from the runnable state will a thread enter the running state.
Blocked State
• When the thread is alive, i.e., the thread class object persists, but it cannot be selected for execution by the
scheduler. It is now inactive.
Dead State
• When a thread's run() function ends the execution of sentences, it automatically dies or enters the dead state.
• That is, when a thread exits the run() process, it is terminated or killed.
• When the stop() function is invoked, a thread will also go dead.
Java Thread Priorities
Priority of a thread describes how early it gets execution and selected
by the thread scheduler.
In Java, when we create a thread, always a priority is assigned to it.
In a Multithreading environment, the processor assigns a priority to a
thread scheduler.
The priority is given by the JVM or by the programmer itself
explicitly.
The range of the priority is between 1 to 10 and there are three
constant variables which are static and used to fetch priority of a
Thread.
Con…
1. public static int MIN_PRIORITY
It holds the minimum priority that can be given to a thread.
The value for this is 1.
2. public static int NORM_PRIORITY
It is the default priority that is given to a thread if it is not
defined. The value for this is 5.
3. public static int MAX_PRIORITY
It is the maximum priority that can be given to a thread. The
value for this is 10.
Get and Set methods in Thread priority
public final intgetPriority()
• In Java, getPriority() method is in java.lang.Thread package. it is used
to get the priority of a thread.
public final void setPriority(intnewPriority)
• In Java setPriority(intnewPriority) method is in java.lang.Thread
package. It is used to set the priority of a thread.
• The setPriority() method throws IllegalArgumentException if the
value of new priority is above minimum and maximum limit.
Example
1)
Process-based Multitasking
(Multiprocessing)
Each process has an address in memory.
In other words, each process allocates a separate memory area.
A process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another requires some time for saving
and loading registers, memory maps, updating lists, etc.
Thread-based Multitasking (Multithreading)
Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.
Thread synchronization
Multi-threaded programs may often come to a situation where multiple
threads try to access the same resources and finally produce erroneous and
unforeseen results.
So it needs to be made sure by some synchronization method that only one
thread can access the resource at a given point in time.
Java provides a way of creating threads and synchronizing their tasks using
synchronized blocks.
Synchronized blocks in Java are marked with the synchronized keyword.
A synchronized block in Java is synchronized on some object.
All synchronized blocks synchronize on the same object can only have one
thread executing inside them at a time.
All other threads attempting to enter the synchronized block are blocked until
the thread inside the synchronized block exits the block.
Con…
All other threads attempting to enter the synchronized block are blocked until
the thread inside the synchronized block exits the block.
This synchronization is implemented in Java with a concept called monitors.
Only one thread can own a monitor at a given time.
When a thread acquires a lock, it is said to have entered the monitor.
All other threads attempting to enter the locked monitor will be suspended until
the first thread exits the monitor.
import java.io.*; // Class for send a message using Threads // Class for send a message using Threads
import java.util.*; class ThreadedSend extends Thread class ThreadedSend extends Thread
{ {
private String msg; private String msg;
// A Class used to send a message Sender sender; Sender sender;
class Sender
{ // Receives a message object and a string // Receives a message object and a string
public void send(String msg) // message to be sent // message to be sent
{ ThreadedSend(String m, Sender obj) ThreadedSend(String m, Sender obj)
System.out.println("Sending\t" + msg ); { {
try msg = m; msg = m;
sender = obj; sender = obj;
{ } }
Thread.sleep(1000);
} public void run() public void run()
catch (Exception e) { {
{ // Only one thread can send a message // Only one thread can send a message
System.out.println("Thread interrupted."); // at a time. // at a time.
} synchronized(sender) synchronized(sender)
{ {
System.out.println("\n" + msg + "Sent"); // synchronizing the send object // synchronizing the send object
} sender.send(msg); sender.send(msg);
} } }
} }
} }
// Driver class
class SyncDemo
{
public static void main(String args[])
{
Sender send = new Sender();
ThreadedSend S1 =
new ThreadedSend( " Hi " , send );
ThreadedSend S2 =
new ThreadedSend( " Bye " , send );