Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 42

Presentation by:

Chakradhar
Multi Threaded
Programming
PROGRAMMING

PROCESS BASED THREAD BASED


PROGRAMMING PROGRAMMING
THREAD
• Thread is a code of execution in a
programme .
• Every thread is an independent with
its own path of execution.
• JVM allows to execute more than one
Thread concurrently which is called
as Multithreading.
• Every Thread will have a Name,
Thread Group and Priority by default.
MULTI THREAD
• If an application is having more than
one path of executions.
• One process having multiple pieces of
codes with their own path of
executions.

• Context Switching is the mechanism


implemented in multi tasking or multi
threading.
MULTI THREAD
RAM

MULTI THREAD

TASK(S)

MULTI PROCESSING

• Each task is associated with the process


• All the tasks are within single process.
SCHEDULING
Scheduling is process of switching
between the tasks.
• Pre-emptive Multi Tasking: priority
based.
• Time Slicing: divides available time
among available tasks with same
priority.
• Cooperative Environment: voluntarily
giveup the control (yielding)
THREAD SCHEDULING
• No standard scheduling is defined in
multi threading.

• It depends on Operating system


schedulers.

• Hence try to control from application


rather than depending on
environment.
THREAD STATES
Thread Registration
start() READY

RUNNING

WAIT SUSPEND SLEEP BLOCKED


THREAD
Preparation of Thread Code

implements extends
Runnable Thread

override a method
public void run()
{
statements;
}
Runnable Implementation
class NewThread implements Runnable
{
variable declaration;
NewThread()
{
variable initialisation;
}
public void run()
{
thread code
}
}
Thread of Runnable type
Creating an instance of runnable object
NewThread r = new NewThread();

Converting runnable object into Thread


Thread t=new Thread(r);

Registering a Thread
t.start();
Extending a Thread
class NewThread extends Thread
{
variable declaration;
NewThread()
{
variable initialisation;
}
public void run()
{
// thread executable code
}
}
Creating a Thread

Creating an instance of Thread object


NewThread t = new NewThread();

Registering a Thread
t.start();
Thread Attributes

MAX_PRIORITY  10

MIN_PRIORITY  1

NORM_PRIORITY  5
Thread Constructors
Thread()
Thread(String)
Thread(Runnable)
Thread(Runnable, String)
Thread(ThreadGroup, String)
Thread(ThreadGroup,Runnable)
Thread(ThreadGroup,Runnable,String)
Thread Methods
Thread t=Thread.currentThread()
t.start()
t.join()
t.sleep(long time)
t.yield()

t.setPriority(int)
t.setDaemon(boolean b)
String name = t.getName()
boolean b = t.isAlive()
Daemon Thread
These are Threads which will execute in
background without our knowledge.
If Daemon threads are the only threads
running in JVM then quits since there are
no threads to which services can be given.

Child Threads created from Daemon thread


will become daemon threads

Example : Garbage Collector

Method : setDaemon(true);
Inter Thread Communication
Communication between Threads in a multithreading
system is important. A Thread which share resources
must communicate in order to coordinate their
efforts, as well as to prevent situations in which one
process disrupts another. In instances where two or
more Threads are working together, synchronization
becomes an issue.
1. Resources Sharing (wait & notify)
2. Process Synchronisation (Synchrozation)

Inter process comminication:


http://www.cne.gmu.edu/modules/ipc/term-index.html
Thread Racing/Monitor
• All the threads trying to access the same
resource is called Thread Racing.

• This Racing leads in mixed results of


different threads as every thread will
interact with same resource cuncurrently.

• Sema phore concept is used to prevent


the Thread Racing.
Thread Racing/Monitor
Sema phore is a memory flag used in o.s.
which is used to check the availability of
resource.
• >=1 indicates then resource is busy.
• 0 indicates resource is freely available.

Semaphores can have a value of 0 (meaning no


Wakeups are saved), or a positive integer value,
indicating the number of sleeping processes.

Sema phore is called as “Monitor”


Thread Racing/Monitor
Sleeping
Semaphore Value
Processes

S1 0 T1
S2 3 0
S3 0 T4 T5
there are 3 semaphores in above diagram:
S1 has a value of zero and Thread T1 is blocked on S1
S2 has a value of three, meaning three more Threads
may execute a down operation on S2 without being
put to sleep
S3 has a value of zero, and has two sleeping Threads,
T4 and T5, blocked on it.
Thread Racing/Monitor
Sleeping
Semaphore Value
Processes

S1 0 0
S2 3 0
S3 0 T4 T5

when a Thread executes an UP on S1, Thread T1 is


activated by an UP operation. It executes a DOWN
on S1 and enters its critical section. The state of
the semaphores after these actions has now
changed.
Thread Monitor
• Controlling access to resources by
allowing only one thread at any given
time to use resource.

• To implement the Monitoring/Sema


Phore concept a Locking mechanism
has to be implemented on object or
resource which is called as
“Synchronization”
Synchronization
Synchronized is a keyword used to
privent racing.

Different ways using Synchronized:


1. Method Synchronization
2. Synchronizing non synchronized
methods
3. Critical / Atamic code (Lock on object)
Synchronization
1st Method Synchronisation:

class Resource
{
synchronized void fileRead(String file)
{
System.out.println(“[started “+file);
Thread.currentThread().sleep(1000);
System.out.println(“end of “+file+”]”);
}
}
Synchronization
class UseThread extends Thread
{
Resource res;
String file;
UseThread(String file, Resouce res)
{
this.res=res;
this.file=file;
this.start();
}
public void run()
{
res.fileRead(file);
}
}
Synchronization
class SyncDemo
{
public static void main(String[] args)
{
System.out.println(“Start of main application”);
Resource r=new Resource();
UseThread ut1=new UseThread(“ABCD”, r);
UseThread ut2=new UseThread(“XYZ”, r);
try
{
ut1.join(); ut2.join();
}
catch(Exception e){e.printStackTrace();}
System.out.println(“End of mail Application”);
}
}
Synchronization
2nd Method Synchronisation:
this is process of monitoring the resources
which are non synchronized from using class.

Example:
public void run()
{
synchronized (res)
{
res.readFile(file);
}
}
Synchronization
3rd Method Synchronisation:
Critical or Atamic code is a code which should
execute by acquiring lock on object which is
providing services through the code.
Example: Example:
public void run() public void readFile(String file)
{ {
simple code; simple code;
synchronized (this) synchronized (this)
{ {
critical code; reading of file;
} }
simple code; simple code;
} }
Inter Thread Communication

Resources Sharing (wait & notify)


Some form of mutual exclusion is
needed in order to prevent two
processes from entering their Critical
Sections at the same time.
Inter Thread Communication
Thread associated methods:
• wait()
– If wait is encountered on any object, thread
gives up the monitor on that object and goes
to sleep until it is notified.
• notify()
– wakes up the first thread that released the
monitor and went to sleep.
• notifyAll()
– wakes up all the threads which are in waiting
mode by giving up the monitor.
Inter Thread Communication
class Product
{
int count;
boolean flag=true;
synchronized void put(int count)
{
if(!flag) wait();
this.count=count;
System.out.println(“added product of “+this.count);
flag=false;
notify();
}
Inter Thread Communication
synchronized void get(int count)
{
if(flag)
{
wait();
}
System.out.println(“got the item no…”+this.count);
flag=true;
notify();
}
}
Thread Dead Lock
It is a special type of blocked state where
threads are circularly dependent on each
other ie., if the resources held by a thread
is required by another thread and
wiseversa.
A B
1

Call B.2 Call A.2

2 2
Thread Dead Lock
class A
{
synchronized void one(B ob)
{
System.out.println(“ In one of A”);
Thread.sleep(1000);
ob.two();
}
synchronized void two()
{
System.out.println(“ In two of A”);
}
}
Thread Dead Lock
class B
{
synchronized void one(A oa)
{
System.out.println(“ In one of B”);
Thread.sleep(1000);
oa.two();
}
synchronized void two()
{
System.out.println(“ In two of B”);
}
}
Thread Dead Lock
class Thread1 extends Thread
{
A oa; B ob;
Thread1(A oa, B ob)
{
this.oa=oa;
this.ob=ob;
}
public void run()
{
oa.one(ob);
}
}
Thread Dead Lock
class Thread2 extends Thread
{
A oa; B ob;
Thread1(A oa, B ob)
{
this.oa=oa;
this.ob=ob;
}
public void run()
{
ob.one(oa);
}
}
Thread Communication
PipedThread with Thread with
POS.write(byte) PIS.read()

byte PipedOutputStream PipedInputStream byte

PipedOutputStream pos=new PipedOutputStream();


PipedInputStream pis=new PipedInputStream(pos);
PipedThread pt=new PipedThread(pos);
Int n=pis.read();
Thread Goup
• It is a collection through which we
can control more than one thread.

• Every thread created in java


belongs to Group.

• If group is not specified explicitly


then it belongs to the same group
as its parent belongs to.
Thread Goup
Constructors:
ThreadGroup(String name)
ThreadGroup(ThreadGroup parent, String name)

Methods:
setMaxPriority(int p)
setDaemon(boolean b)
activeCount()
enumerate(Thread[ ] tlist)
enumerate(ThreadGroup[ ] tlist)

You might also like