You are on page 1of 32

Chapter one

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.

1. By extending Thread class


In this case, a thread is created by a new class that extends the Thread
class, creating an instance of that class.
The run() method includes the functionality that is supposed to be
implemented by the Thread.
Example
class Multi extends Thread{ //new class that extends the Thread class
public void run(){ //The run() method includes the functionality that is supposed
to be implemented by the Thread.
System.out.println("thread is running..."); //
}
public static void main(String args[]){
Multi t1=new Multi(); //creating an instance of that class.
t1.start(); //create a new thread and to make it runnable
}
}
Con…
• The start() method is used to call the void run() method.
• When start() is called, a new stack is given to the thread, and run() is invoked to introduce a new
thread in the program.
2. Implementing Runnable interface
• This is the easy method to create a thread among the two.
• In this case, a class is created to implement the runnable interface and then the run() method.
• The code for executing the Thread should always be written inside the run() method.
• Here's a code to make you understand it.
Example
1. class Multi implements Runnable{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi m1=new Multi();
7. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
8. t1.start();
9. }
10.}
public class MyThread1
{
// Main method
public static void main(String argvs[])
{
// creating an object of the Thread class using the constructor Thread(String name)
Using the Thread Class: Thread(String Name) Thread t= new Thread("My first thread");

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

class MyThread extends Thread


• {
• public void run()
• {
• System.out.println("Thread Running...");
 If we don’t set thread priority of a thread then by
• }
default it is set by the JVM.
• public static void main(String[]args)
 In this example, we are getting thread’s default
• {
priority by using the getPriority() method.
• MyThread p1 = new MyThread();
• MyThread p2 = new MyThread();
• MyThread p3 = new MyThread();
• p1.start();
• System.out.println("P1 thread priority : " + p1.getPriority());
• System.out.println("P2 thread priority : " + p2.getPriority());
• System.out.println("P3 thread priority : " + p3.getPriority());

• }
• }
Example 2

 We can fetch priority of a thread by using some predefined


constants provided by the Thread class.
 these constants returns the max, min and normal priority of
a thread.
• class MyThread extends Thread
• {
• public void run()
• {
• System.out.println("Thread Running...");
• }
• public static void main(String[]args)
• {
• MyThread p1 = new MyThread();
• p1.start();
• System.out.println("max thread priority : " + p1.MAX_PRIORITY);
• System.out.println("min thread priority : " + p1.MIN_PRIORITY);
• System.out.println("normal thread priority : " + p1.NORM_PRIORITY);
• }
• }
Exemple 3

 To set priority of a thread, setPriority() method of thread class is


• class MyThread extends Thread used.
 It takes an integer argument that must be between 1 and 10. see the
• {
below example.
• public void run()
• {
• System.out.println("Thread Running...");
• }
• public static void main(String[]args)
• {
• MyThread p1 = new MyThread();// Starting thread
• p1.start();// Setting priority
• p1.setPriority(2);// Getting priority
• int p = p1.getPriority();
• System.out.println("thread priority : " + p);
• }
• }
• class MyThread extends Thread
• {
• public void run()
• {
• System.out.println("Thread Running... "+Thread.currentThread().getName());
• }
• public static void main(String[]args)
• {
• MyThread p1 = new MyThread();
• MyThread p2 = new MyThread(); // Starting thread
 In this example, we are setting priority of two
• p1.start();
thread and running them to see the effect of thread
• p2.start(); // Setting priority
priority.
 Does setting higher priority thread get CPU first.
• p1.setPriority(2); // Getting -priority
See the below example.
• p2.setPriority(1);
• int p = p1.getPriority();
• int p22 = p2.getPriority();
• System.out.println("first thread priority : " + p);
• System.out.println("second thread priority : " + p22);

• }
• }
Multithreading in Java
In Java, multithreading is the method of running two or more threads at the same
time to maximize CPU utilization.
As a result, it is often referred to as Concurrency in Java.
Each thread runs in parallel with the others.
 Since several threads do not assign different memory areas, they conserve memory.
 Furthermore, switching between threads takes less time.
In Java, multithreading enhances program structure by making it simpler and easier
to navigate.
These generalized threads can be used in high-server media applications to easily
change or enhance the configuration of these complex structures.
Here is an example of Multithreading in Java.
A thread is a lightweight sub-process, the smallest unit of processing.
 Multiprocessing and multithreading, both are used to achieve multitasking.
Advantages of Java Multithreading
 It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.
 You can perform many operations together, so it saves time.
 Threads are independent, so it doesn't affect other threads if an exception occurs in
a single thread.
Multitasking

Multitasking is a process of executing multiple tasks simultaneously.


We use multitasking to utilize the CPU. Multitasking can be achieved
in two ways:
 Process-based Multitasking (Multiprocessing)
 Thread-based Multitasking (Multithreading)

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 );

// Start two threads of ThreadedSend type


S1.start();
S2.start();

// wait for threads to end


try
{
S1.join();
S2.join();
}
catch(Exception e)
{
System.out.println("Interrupted");
}
}
}

You might also like