0% found this document useful (0 votes)
22 views22 pages

Chapter 8 Multithreading

Uploaded by

tiashamandal91
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views22 pages

Chapter 8 Multithreading

Uploaded by

tiashamandal91
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

MULTITHREADED PROGRAMMING

IN JAVA

Pratima Sarkar
CSE TINT
Table of Contents
• What is Thread?
• Creating Java Threads
• Extending the Threads Class
• Stopping and Blocking a Thread Life cycle of a
Thread
• Using Thread methods,
• Thread Exceptions,
• Thread priority
• Synchronization,
• Implementing the ‘Runnable’ Interface.
Introduction
• Difference between program and process.
– A program is a set of instructions that are written to perform a
designated task.
– A process is an operation which takes the given particular instructions
and perform the manipulations. (Program in execution)

• Single processor V/s Multitasking System.

• Example of single threaded program (A thread is a program that has a single


flow of control)

class ABC Beginning


{ ………………
……………… Single threaded body of execution
………………
……………… End
}
Introduction
• Multitasking is a process of executing multiple task simultaneously, to
utilize CPU.

• Multitasking can be achieved by two ways:


 Process-based Multitasking(Multiprocessing)
 Thread-based Multitasking(Multithreading)

• Process-based Multitasking (Multiprocessing): Has own address in


memory, Process is heavyweight and Cost of communication between the
process is high(Switching from one process to another require some time)

• Thread-based Multitasking (Multithreading): Has share the same


address space in memory, lightweight and Cost of communication
between the thread is low.
Introduction
• Unique property of java that it supports multithreaded programing.
• A multi-threaded program:
Main thread

Main Method
module

start start start

Switching Switching
• Multithreaded programs are the programs that contains multiple
flow of control.
Introduction
• A thread is a single tiny programs (or module) that runs in parallel with
other.

• A multithreaded programs are the programs that contains multiple flows of


control.

• Threads in java are subprograms of main application programs that share


same memory space. Hence, they are known as lightweight threads or
lightweight process.

• “threads running in parallel” – means flow of execution is shared


between threads.

• Multithreading in java is a powerful programming tool that enables


programmer to do multiple things at one time, can divide long programs
into threads and executes them in parallel.

• Eg of Multithreading: Sending some task like printing into background


and continue performing task in foreground.
Introduction
• Multitasking Multithreading
1. It is an OS concept in which 1. Its is a programming concept in which
multiple task are executed program/process are divided into 2 or more
simultaneously. subprograms/threads that are executed at
same time in parallel.
2. Its supports execution of multiple 2. Its supports execution of multiple parts of
programs simultaneously. single programs simultaneously.
3. The processor has to switch 3. The processor has to switch between
between different programs/processes. different threads.
4. Less efficient 4. Highly efficient
5. Process/ program is the smallest 5.A thread is a smallest unit in
unit in multi-tasking environment. Multithreading.
6. Helps in developing efficient OS. 6. Helps in developing efficient programs.
7. Expensive in case of context 7. Cost effective in case of context
switching. switching.
Creating thread and executing

1. By creating a thread class: Define a class that extends Thread Class and
override its run() method with the code required by the thread.

2. By implementing a runnable interface: runnable interface has only one method


“run”, into which code is to be written that is to be executed by thread.

3. Syntax for declaring own thread class and implementing a run(method):


class MyThread extends Thread
{
public void run()
{ ………..
………..
}
}

4. Syntax for creating a thread and run an instance of our own thread class:
MyThread aThread= new MyThread();
aThread.start();
Example
Class A extends Thread Class MyThread
{ public void run() {
{ …….. P.S.V.M(String args[])
…….. {
} A aThread= new A();
} B bThread= new B();
Class B extends Thread C cThread= new C();
{ public void run()
{ …….. aThread.start();
…….. bThread.start();
} cThread.start();
}
Class C extends Thread }
{ public void run() }
{ ……..
……..
}
}
Thread Life Cycle model
• A thread can be in one of the five states (New, Runnable, Running,
Blocked, Dead)

New Born
Active Thread Start Stop

Stop
Running Runnnable Dead
Yield

Sleep Resume Stop


Suspend Notify
wait Blocked

Sleep: Blocked for specified time.


Suspend: Blocked until further orders.
Wait: Blocked until certain condition occurs.
Thread Life Cycle model
1. New: The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.

2. Runnable: The thread is in runnable state after invocation of start() method,


but the thread scheduler has not selected it to be the running thread.

3. Running: The thread is in running state if the thread scheduler has selected
it.

4. Blocked (Non-Runnable): This is the state when the thread is still alive, but
is currently not eligible to run.(Prevented from entering runnable state)

5. Dead (Terminated): A thread is in terminated or dead state when its run()


method exit.
Creation of threads
• Threads are implemented in the form of object that contain a
method called run.

• run() method should be invoked by an object of concerned thread.

• This can be achieved by the thread object and initiating it with the
help of another method called start().

• Two ways of creating thread:


– By extending Thread class
– By implementing Runnable interface
By extending Thread class

• Declare a class extends thread class


• Implement run() method
• Create Thread class object.
• Call start() by using object.
By extending Thread class Example
class A extends Thread class thr
{
{
public void run()
{ p.s.v.m(String args[])
for(int i=0;i<10;i++) {
SOP("\n from thread class A "+i); A a1=new A();
} B b1=new B();
}
class B extends Thread
a1.start();
{ b1.start();
public void run() }
{ } from thread class A :0
for(int i=0;i<10;i++)
from thread class A: 1
SOP("\n from thread class B "+i);
} from thread class B :0
} from thread class A: 2
from thread class B: 1
By implementing Runnable interface
• Declare a class as implementing the Runnable interface.

• Implement the public void run().

• Create a thread by defining object that is initiated from


this Thread class as the target of thread.

• Call start() method to run the thread.


By implementing Runnable interface
Class X implements Runnable Class InterT
{ {
public void run() p.s.v.m(String args[])
{
{
for(int i=1; i<=19;i++)
{ X t1=new X();
s.o.pln(“Thread \t” + i); Thread t2=new Thread(t1);
} t2.start();
} }
} }
Threads priority
• Each thread have a priority. Default value is 5.

• Priorities are represented by a number between 1


and 10. In most cases, thread schedular
schedules the threads according to their priority
(known as preemptive scheduling).

• But it is not guaranteed because it depends on


JVM specification that which scheduling it
chooses.
Threads priority
class A extends Thread class thr
{ {
public void run() p.s.v.m(String args[])
{ {
for(int i=0;i<10;i++) A a1=new A();
SOP("\n from thread class A "+i); B b1=new B();
}
} a1.setPriority(Thread.MIN_PRIORITY);
class B extends Thread
{ b1.setPriority(Thread.MAX_PRIORITY);
public void run()
{ a1.start();
for(int i=0;i<10;i++) b1.start();
SOP("\n from thread class B "+i); }
} }
}
How to block a Thread?
class A extends Thread class syn11
{
static int i=0; {
public void run() p.s.v.m(String args[])
{
try{ i=i+5; {
Thread.sleep(1000); A a1=new A();
SOP("value of i : "+i);
} A a2=new A();
catch(InterruptedException e) a1.start();
{ SOP ("error"); }
}
a2.start();
Output
Value of i :10
} } Value of i :10

}
Synchronization
 Synchronization in java is the capability to control the
access of multiple threads to any shared resource.

 When two or more threads needs to access a share


resource, they need some to ensure that the resource will
be used by only one thread at a time. The process by
which this was achieved is called synchronization.
Why Synchronization ?
class A extends Thread class syn11
{
static int i=0; {
public void run() p.s.v.m(String args[])
{
try{ i=i+5; {
Thread.sleep(1000); A a1=new A();
SOP("value of i : "+i);
} A a2=new A();
catch(InterruptedException e) a1.start();
{ SOP ("error"); }
}
a2.start();
Output
Value of i :10
} } Value of i :10

}
Use of synchronized method to achieve
synchronization.
class A extends Thread class syn12
{ A a;
static int i=0; {
A() { } p.s.v.m(String args[])
A(A x) { a=x; }
public void run() {
{ a.print(); }//end run A a1=new A();
synchronized void print()
{ A a2=new A(a1);
try{ i=i+5; A a3=new A(a1);
Thread.sleep(1000);
SOP("value of i : "+i);
} a2.start();
catch(InterruptedException e)
a3.start(); Output
{ SOP("error"); }
Value of i : 5
}//end print } Value of i : 10
}
}

You might also like