0% found this document useful (0 votes)
3 views

Java Multi Threading

The document provides an overview of Java threads, explaining concepts such as multitasking, multithreading, and the differences between concurrency and parallelism. It details the advantages of multithreading, threading mechanisms, and the life cycle of a thread, including various states like newborn, runnable, running, blocked, and dead. Additionally, it covers thread scheduling, priority, and synchronization to manage concurrent access to shared resources.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Multi Threading

The document provides an overview of Java threads, explaining concepts such as multitasking, multithreading, and the differences between concurrency and parallelism. It details the advantages of multithreading, threading mechanisms, and the life cycle of a thread, including various states like newborn, runnable, running, blocked, and dead. Additionally, it covers thread scheduling, priority, and synchronization to manage concurrent access to shared resources.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Java Threads

Multitasking and Multithreading


 Multitasking:
 refers to a computer's ability to perform
multiple jobs concurrently
 more than one program are running
concurrently, e.g., UNIX
 Multithreading:
 A thread is a single sequence of execution
within a program.
 Multithreading refers to multiple threads of
control within a single program each
program can run multiple threads of control
within it, e.g., Web Browser
Concurrency vs. Parallelism
CPU CPU1 CPU2
Threads and Processes
CPU

main

run

Process 1 Process 2 Process 3 Process 4

GC
Advantages of multithreading
1. Reduces the computation time.
2. Improves performance of an
application.
3. Threads distribute the same address
space so it saves the memory.
4. Context switching between threads is
usually less costly than between
processes.
5. Cost of communication between
threads is comparatively low.
Applications
 When we execute an application:
1. The JVM creates a Thread object whose
task is defined by the main() method
2. The JVM starts the thread
3. The thread executes the statements of
the program one by one
4. After executing all the statements, the
method returns and the thread dies
A single threaded program
class ABC
{
….
public void main(..) begin

{
… body

..
end
}
} 7
A Multithreaded Program

Main Thread

start
start start

Thread A Thread B Thread C

Threads may switch or exchange data/results


Web/Internet Applications:
Serving Many Users Simultaneously

PC client

Internet
Server
Local Area Network

PDA
Threading Mechanisms...
1. Create a class that extends the
Thread class
2. Create a class that implements the
In Runnable
both cases the interface
run() method should be implemented

10
1st method: Extending
Thread class
 Threads are implemented as objects that
contains a method called run()
class MyThread extends Thread
{
public void run()
{
// thread body of
execution
}
}
 Create a thread:
MyThread thr1 = new MyThread();
 Start Execution of threads:
class MyThread extends Thread {
public void run() {
System.out.println(" this thread is running ... ");
}
}
class ThreadEx1 {
public static void main(String [] args ) {
MyThread t = new MyThread();
t.start();
}
}
2nd method:
Threads by implementing Runnable interface
class MyThread implements Runnable
{
public void run()
{
// thread body of execution
}
}
 Creating Object:
MyThread myObject = new MyThread();
 Creating Thread Object:
Thread thr1 = new
Thread( myObject );
 Start Execution:
A Runnable Object
 When running the Runnable object, a
Thread object is created from the Runnable
object
 The Thread object’s run() method calls
the Runnable object’s run() method
 Allows threads to run inside any object,
regardless of inheritance
An example
class MyThread implements Runnable {
public void run() {
System.out.println(" this thread is
running ... ");
}
}
class ThreadEx2 {
public static void main(String [] args ) {
MyThread o=new MyThread();
Thread t = new Thread(o);
t.start();
}
A Program with Three Java
Threads
 Write a program that creates 3 threads

class A extends Thread


{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("\t From
ThreadA: i= "+i);
}
System.out.println("Exit from
A");
}
class B extends Thread {
public void run()
{
for(int i=6;i<=10;i++)
{
System.out.println("\t From ThreadB: i=
"+i);
}
System.out.println("Exit from
B");
}
}
class C extends Thread {
public void run()
{
for(int i=11;i<=15;i++) {
System.out.println("\t From
ThreadC: i= "+i);
}
System.out.println("Exit from
C");
}
}
class ThreadTest
{
public static void
main(String args[])
{
A obA=new A();
B obB=new B();
C obC=new C();
obA.start();
obB.start();
Thread Methods
void start()
 Creates a new thread and makes it
runnable
 This method can be called only once.
aThread.start()
void run()
 The new thread begins its life inside
this method
Stopping a Thread
 Whenever we want to stop a thread
from running further, call stop()
method
aThread.stop()
 This method causes the thread to
move to dead state.
 The stop may used when the
premature death of thread is
desired.
Blocking a Thread
 A thread can also be temporarily
suspended or blocked from entering
into the runnable and running state by
using following methods.
 sleep() :blocked for specified time
 suspend() :blocked until further orders
( resume() )
 wait() :blocked until certain conditions
occurs (notify())
 These methods causes the thread to go
into blocked state.
Thread Methods
void yield()
 Causes the currently executing thread
object to temporarily pause and allow
other threads to execute.
 Allow only threads of the same priority to

run.
void sleep(int m) or sleep(int m,
int n)
 The thread sleeps for m
Life Cycle of Thread
 During Life time of a thread there are many
states it can enter.
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
 A thread is always in one of these five states.
 It can move from one state to another via a
variety of ways.
Thread State Diagram
Newborn
new ThreadExample(); Thread
stop(
thread.start(); )

Active Runnable run()


Thread Running
Running Dead Thread
method
yield returns

wait() resume()
sleep() notify() stop(
Suspend() )

Idle Thread Blocked


Not
Runnable
Newborn State
 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 the following
things Newbor
n

stop();
start();

Runnable Dead Thread


Runnable State
 Means that thread is ready for execution and
is waiting for the availability of the
processor.
 That is , thread has joined the waiting queue.
 Threads with equal priority are scheduled in
round robin fashion. i.e. (FCFS)
 However, a thread can relinquish control to
another thread by using yield() method.
yield()

Runnable Threads
Running Thread
Running State
 Running means that processor has given its time
to the thread for its execution.
 The thread runs until it relinquishes control on
its own or it is interrupted by higher priority
thread.
 The running thread may relinquish its control in
one of the following situations.
1. It has been suspended using suspend()
method.
2. It has been made to sleep
3. It has been told to wait until some event occurs.
1. It has been suspended using suspend() method.
suspend()

resume()

Running Runnable Suspended

2. It has been made to sleep sleep(t)

after(t)

Running Runnable Suspended

3. It has been told to wait until some event occurs


wait

notify

Runnable Waiting
Running
Blocked State
 A thread is blocked when it is prevented from
entering into the runnable and running state.
 This happens when thread is suspended,
sleeping, or waiting in order to satisfy certain
requirements.
 A blocked thread is “not runnable” but not
dead and therefor fully qualified to run again.
Dead State
 Every thread has life cycle. A thread ends its
life when it has completed its execution. It is
natural death.
 However we can kill it by sending the stop
Demo
ThreadMethods
Scheduling Threads
start()
Ready queue

Newly created
threads

Currently executed
thread
I/O operation completes

• Waiting for I/O operation to be completed


• Waiting to be notified
• Sleeping
• Waiting to enter a synchronized section
Preemptive Scheduling
 Preemptive scheduling – the thread
scheduler preempts (pauses) a running
thread to allow different threads to
execute.

 Nonpreemptive scheduling – the


scheduler never interrupts a running
thread.
Thread Priority
 Every thread has a priority.
 When a thread is created, it
inherits the priority of the thread
that created it.
 The priority values range from 1 to
10, in increasing priority.
Thread Priority (cont.)
 The priority can be adjusted
subsequently using the setPriority()
method
Threadname.setPriority(intNumber);
 The priority of a thread may be obtained
using getPriority()
 Priority constants are defined:
 MIN_PRIORITY=1 The main thread is
 MAX_PRIORITY=10 created with priority
 NORM_PRIORITY=5 NORM_PRIORITY
Synchronization
 In Java, the threads are executed
separately to each other. These
threads are called as asynchronous.
 But what if two threads try to use
same data?
 For example, one thread may try to
read record from a file while another is
still writing to same file.
 Depending on the situation we may
get strange results.
Synchronization
 Java enables us to overcome this using
synchronization.
 Keyword synchronized helps to solve such
problems.
 The method that will read the file and method that
will update file may be declared as synchronized.

synchronized void update()


{
…….
}
Synchronization
 Java creates a “monitor” and hands it
to the thread that calls the method first
time.
 As long as the method holds the
monitor, no other thread can enter the
synchronized section of code.
 A monitor is like a key and the thread is
that holds the key can only open the
lock.
 Whenever a thread has completedDemo
its
SynThread1.java

You might also like