Multithreading(Concurrency)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Thread
A thread in Java is a lightweight unit of execution. It represents a single path
of code that runs independently but shares memory and system resources
with other threads in the same program.
A thread is a subset(part) of the process.
A process consists of multiple threads. A thread is a smallest part of the
process that can execute concurrently with other parts(threads) of the
process.
Java makes it easy to work with threads using the built-in Thread class and
other concurrency tools in the [Link] package.
By default, every Java application starts with one main thread, which begins
executing the main() method. From there, you can create additional threads
to run tasks concurrently.
In Java, when you run a program, the Java Virtual Machine (JVM) starts a
process. Inside that process, the JVM can run multiple threads to perform
different tasks.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Multithreading
• Multithreading is an important concept in Java that allows a program to
do many things at the same time. Instead of running tasks one after
another, a multithreaded program can run multiple tasks in parallel,
making better use of system resources and improving performance.
• ‘threads running in parallel’ does not really mean that they actually run
at the same time. Since all the threads are running on a single processor,
the flow of execution is shared between the threads. The java
interpreter handles the switching of control between the threads in such
a way that it appears they are running concurrently
• multithreading means running multiple “threads” of execution within a
single program. A thread is like a small, independent path of execution.
• Java supports multithreading through built-in features. Each thread runs
separately but shares the same memory space, which allows them to
work together efficiently, but also means they need to coordinate
carefully to avoid conflicts.
Examples: Web Servers ,Games,GUI Applications,etc.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Life Cycle of thread
A Java thread goes through several stages in its
lifetime. These stages are managed by the JVM and
the operating system.
Here are the main stages in the thread lifecycle:
1. New: When we create a thread object, the thread is
born and is said to be in newborn state. The thread is
not yet scheduled for running. At this state, we can
do only one of the following with it:
Schedule it for running using start()
method. Kill it using stop() method
If scheduled, it moves to the runnable state. If we
attempt to use any other method at this stage, an
exception will be thrown.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Contd…
2. Runnable: The runnable state means that the thread is ready for execution and is
waiting for the availability of the processor.
That is, the thread has joined the queue of threads that are waiting for
execution.
If all threads have equal priority, then they are given time slots for execution in
round robin fashion. i.e. first-come, first-serve manner.
If we want a thread to relinquish control to another thread of equal priority
before its turn comes, we can do so by using the yield() method.
The thread is ready to run and waiting for CPU time. It’s like the worker is standing
by, ready to work when given the chance.
[Link](); Releasing Control Using yield()
Yield()
…….... ……....
.. ..
Runnable
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson
Thread Education, Inc. All
rights reserved. 0-13-222158-6
Contd…
3. Running: Running means that the processor has given its time to the thread
for its [Link] thread runs until it relinquishes control on its own or it is
preempted by a higher priority thread.
A running thread may relinquish its control in one of the following situations:
Suspend() and resume() Methods:-This approach is useful when we want to
suspend a thread for some time due to certain reason, but do not want to kill
it.
suspended
resume
Running Runnable Suspended
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Contd…
Sleep() method:This means that the thread is out of the queue during this time
period. The thread re-enter the runnable state as soon as this time period is
elapsed. sleep(t)
after(t)
Sleeping
Wait() and notify() methods :- blocked until certain condition occurs
wait
notify
Running Runnable Waiting
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Contd…
4. Blocked State: A thread is said to be blocked when it is prevented form entering
into the runnable state and subsequently the running state.
This happens when the thread is suspended, sleeping, or waiting in order
to satisfy certain requirements.
A blocked thread is considered “ not runnable” but not dead and therefore fully
qualified to run again.
5. Dead State:
A running thread ends its life when is has completed executing its run() method.
It is a natural death.
However, we can kill it by sending the stop message to it at any state thus
causing a premature death to it.
A thread can be killed as soon it is born, or while it is running, or even when it is
in “not runnable” (blocked) condition.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Contd…
State diagram of a thread
New Newbor
Thread n
start
stop
Active
Runnin Runnabl
Thread stop Dead
g yield e
Killed
Thread
suspended resume stop
sleep after
wait notify
Idle Blocked
Thread
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Creating Threads in java
In Java, there are several ways to create and run threads. Each approach
has its own use cases, and choosing the right one depends on how your
application is structured. Here, we’ll cover the three main ways to create
threads:
Extending the Thread class
Implementing the Runnable interface
Using lambda expressions (Java 8 and later)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Contd…
Extending the thread class: One of the simplest ways to create a thread in Java is by
extending the built-in Thread class and overriding its run() method. This method
contains the code that should run in the new thread. Staring New Thread.
Example :
public class MyThread extends Thread
{
public void run()
{
[Link]("Thread is running...");
}
public static void main(String[] args)
{
MyThread thread = new MyThread();
[Link](); // Start the thread }
}
The run() method defines the task the thread will perform. The start() method tells the JVM
to start a new thread and execute run() in parallel with the main thread.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Contd…
Implementing the Runnable Interface: A more flexible way to create threads is to
implement the Runnable interface. This separates the task from the thread itself,
which is useful when you want your class to extend another class.
Declare a class that implements the Runnable interface.
Declare the run() method
Create a thread by defining an object that is instantiated from this “runnable”
class as the target of the thread
Call the threads start() method to run the thread.
The application can start an instance of the thread by using the following
code:
RunnableY ry = new RunnableY();
Thread ty= new Thread(ry);
[Link]();
1st line instantiate the RunnableY class.
2nd line instantiate the Thread class. A reference to the RunnableY object is
provided as the argument to the constructor.
Last line starts the thread.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Example
Program:
public class MyRunnable implements Runnable
{
public void run()
{
[Link]("Runnable thread is running...");
}
public static void main(String[] args)
{
Thread thread = new Thread(new MyRunnable());
[Link]();
}}
This method is more flexible than extending Thread. It encourages better
separation of concerns and allows you to reuse the same task with different
threads.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Contd…
Using Lambda Expression: This is ideal for short, one-off tasks where you don’t want to write
a full class.
Example:
public class LambdaThread
{
public static void main(String[] args)
{
Thread thread = new Thread(() ->
{
[Link]("Thread running with lambda!");
});
[Link]();
}}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Commonly used methods of Thread
class
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the [Link] calls the run() method
on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily
cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Synchronization
Synchronization is about to control the access of threads on shared resources in the
program.
In Java, each object has a lock. A thread can acquire the lock for an object by using
synchronized keyword.
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 process by
which this is achieved is called synchronization.
This can be done in two ways. First, a method can be synchronized by using the
synchronized keyword as a modifier in the method declaration.
When a thread begins executing a synchronized instance method, it automatically
acquires a lock on that object.
The lock is automatically relinquished when the method [Link] one
thread has this lock at any time.
Therefore, only one thread may execute any of the synchronized instance methods for
that same object at a particular time.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Contd…
Another way to synchronize access to common data is via a synchronized
statement block. This has the following syntax:
synchronized(obj)
{
//statement block
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
class Printable class Thread2 extends Thread{
{ Printable t;
synchronized void showTable(int x) Thread2(Printable t){
{ this.t=t;
for(int i=1;i<=10;i++){ }
[Link](x*i); public void run(){
try{ [Link](5);
[Link](400); }
} }
catch(Exception ex){ class SynchronizationEx{
[Link](ex); public static void main(String args[]) throws
} }}} InterruptedException {
class Thread1 extends Thread{ Printable obj=new Printable();
Printable t; Thread1 t1=new Thread1(obj);
Thread1(Printable t){ Thread2 t2=new Thread2(obj);
this.t=t; [Link]();
} [Link]();
public void run(){ }
[Link](2); }
}
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Inner Class
• In Java, an inner class is a class defined within another class.
• These are also known as non-static nested classes.
• The primary purpose of inner classes is to group logically related classes,
enhance encapsulation, and improve code readability and
maintainability.
Types of Inner Class
1. Member Inner Class
2. Method local Inner Class
3. Anonymous Inner Class
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Contd…
Member Inner Class: This is the most common type, declared directly
within the outer class, like a member variable or method.
class OuterClass {
int outerVar = 10;
class InnerClass {
void display() {
[Link]("Outer variable: " + outerVar); } }
public static void main(String[] args) {
OuterClass outerObject = new OuterClass();
[Link] innerObject = [Link] InnerClass();
[Link]();
}
}
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Contd…
Method-Local Inner Class: Defined within a method of the
outer class. Their scope is limited to that method.
public class OuterClass {
void myMethod() {
Local inner classes are instantiated
int localVar = 50;
within the method or block where
class LocalInnerClass { they are defined.
void display() {
[Link]("Local variable: " + localVar);
}
}
LocalInnerClass localobj = new LocalInnerClass();
[Link]();
}
public static void main(String[] args) {
OuterClass outerobj = new OuterClass();
[Link]();
}
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Contd…
Anonymous Inner class: An anonymous inner class is a class without a name that is instantiated in place.
It is used to make code more concise and is commonly used in GUI applications and for creating threads.
A class without a name, used for creating single-use objects, often for implementing an interface or
extending a class . - You instantiate an anonymous inner class in the same expression that defines it,
typically used for implementing interfaces or abstract classes.
interface Greeting {
void greet();
}
class Main
{
public static void main(String[] args)
{
Greeting hello = new Greeting()
{
@Override
public void greet()
{
[Link]("Hello from anonymous class!");
} };
[Link]();
}
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6