0% found this document useful (0 votes)
11 views28 pages

Lecture 17 Multithreading

Uploaded by

Abcd Efgh
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)
11 views28 pages

Lecture 17 Multithreading

Uploaded by

Abcd Efgh
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/ 28

Maharaja Agrasen Institute of Technology

CIC-212 Java Programming

Lecture 17
Multithreading
Multithreading

The objectives of this presentation are:

 To understand the purpose of multithreading


 To describe Java's multithreading mechanism
 To explain concurrency issues caused by
multithreading
 To outline synchronized access to
shared resources

UNIT-III Multithreading
What is Multithreading?
 Multithreading is similar to multi-processing.
 A multi-processing Operating System can run
several processes at the same time.

 Each process has its own address/memory space.

 The OS's scheduler decides when each process is


executed.
 Only process is actually executing at any given
one However, the system appears to be running
time.
several programs simultaneously
What is Multithreading?

 Separate processes do not have access to


each other's memory space.
 In a multithreaded application, there are
several points of execution within the same
memory space.

 Each point of execution is called a thread.

 Threads share access to memory.

UNIT-III Multithreading
What are Threads ?
Threads are lightweight processes as the
overhead of switching between threads is less.

Why do we need threads?


 To enhance parallel processing.
 To increase response to the user.
 To utilize the idle time of the CPU.
 Prioritize your work depending on priority.
What Kind of Applications Use
Multithreading?
 Any kind of application which has distinct
tasks which can be performed
independently.
 Any application with a GUI.
 Threads dedicated to the GUI can delegate the
processing of user requests to other threads.
 The GUI remains responsive to the user even
when the user's requests are being processed.

UNIT-III Multithreading
What Kind of Applications Use
Multithreading?
 Any application which requires asynchronous
response
 Network based applications are ideally suited to
multithreading.
 Data can from the network at any time.
 In aarrive
single threaded system, data is queued until
the thread can read the data.
 In a multithreaded system, a thread can be
dedicated to listening for data on the network port.
 When data arrives, the thread reads it immediately
and processes it or delegates its processing to
another thread.
Thread Support in Java

 The Java Virtual machine has its own runtime


threads.
 Used for garbage collection.

 Threads are represented by a Thread class.


 A thread object maintains the state of the thread.
 It provides control methods such as interrupt, start, sleep,
yield, wait.

 When an application executes, the main method is


executed by a single thread.
 If the application requires more threads, the application
must create them.
Thread States
 Threads can be in one of four states.
 Created, Running, Blocked, and Dead.

 A thread's state changes based on:


 Control methods such as start, sleep, yield, wait, notify.
 Termination of the run method.

notify()
Thread() start()
Created Runnable Blocked
sleep()
wait()

run() method terminates

Dead
How does a Thread run?
 The thread class has a run() method.
 run() is executed when the thread's start() method is invoked.

 The thread terminates if the run method terminates.


 To prevent a thread from terminating, the run method must not end.
 run methods often have an endless loop to prevent thread termination.

 One thread starts another by calling its start method.


 The sequence of events can be confusing to those more with a
familiar single threaded model.

Thread1 start() Thread2

Thread Object

run()

UNIT-III Multithreading
Creating threads

 In java threads can be created b y extending the


Thread class or implementing the Runnable
Interface
.
 It is more preferred to implement the Runnable
Interface so that we can extend properties from
other classes.
 Implement the run() method which is the
starting point for thread execution.
Example

UNIT-III Multithreading
Using Runnable
 In the example below, when the Thread object is
instantiated, it is passed a reference to a "Runnable"
object.
 The Runnable object must implement a method called "run“.

 When the thread object receives a start message, it


checks to see if it has a reference to a Runnable object:
 If it does, it runs the "run" method of that object.
 If not, it runs its own "run" method.

Thread1 start() Thread2

Thread Object Runnable Object

run() run()
Running threads
Example
class Mythread implements Runnable{
public void run(){
System.out.println(“Thread Calling t. run () does
Started”);} not start a thread, it is
} just a simple method call.
class mainclass { Creating an object does not
public static void main(String args[]){ create a thread, calling
Thread t = new Thread(new start() method creates the
mythread( )); thread.
// This is the way to instantiate a
thread implementing runnable interface
t.start(); // starts the thread by running
the run method
}
}
Properly Terminating Threads

 In Java 1.1, the Thread class had a stop() method.


 One thread could terminate another by invoking i ts stop()
method.
 However, usin g stop() could lead to deadlocks.
 T he stop() method is now deprecated. DO NOT use the stop
method to terminate a thread.

 The correct way to stop a thread is to have the run


method terminate.
 Add a boolean variable which indicates whether the thread
should continue or not.
 Provide a set method for that variable which can be invoked by
another thread.
Thread Functions

getName - Obtain Thread Name


getPriority - Obtains Thread Priority
isAlive - To determine if a is alive
Join - Thread
Wait for a Thread to terminate
Run - Entry point for a Thread
Sleep - Suspend a Thread for a period of Time
Start - start a Thread by calling its run
Yield - method
To switch over to next Thread
Yield() and Sleep()
 Sometimes a thread can determine that it has
nothing to do.
 Sometimes the system can determine this. ie. waiting
for I/O.

 When a thread has nothing to do, it should not


use CPU
 This is called a busy-wait.
 Threads in busy-wait are busy using up the CPU doing
nothing.
 Often, threads in busy-wait are continually checking
a flag to see if there is anything to do.
Yield() and Sleep()
 It is worthwhile to run a CPU monitor program on your
desktop.
 You can see that a thread is in busy-wait when the CPU monitor
goes up (usually to 100%), but the application doesn't seem to
be doing anything.

 Threads in busy-wait should be moved from the Run


queue to the Wait queue so that they do not hog the
CPU.
 Us e yield() r sleep(time).
 Yieldo simply tells the scheduler to schedule another thread.
 Sleep guarantees that this thread will remain in the wait queue
for the specified number of milliseconds.
Example of yield(), stop(), sleep()

UNIT-III Multit reading


Main Thread
We can obtain reference of main Thread by calling currentThread()
method. static Threa currentThre ()
d ad

Class Demo
{
P.S.V.M(--)
{
Thread t=Thread.currentThread();
S.O.P(“Current Thread:” + t);
t.setName(“My Thread”);
S.O.P(“After name Change” + t);
try
{ for (n=5; n>0;n--)
{System.out.println(n);
Thread.sleep(1000);}
}catch(InterruptedException e)
{ S.O.P(“Main Thread
Interrupted”);}
}
}
Example (Creating Multiple Threads)
Class NT implements Runnable
{ Class Demo
{
String name; Thread t; P.S.V.M(--)
{
NT (String tname) NT one=new NT(“One”);
{
NT two=new NT(“Two”);
name=tname;
NT three=new NT(“Three”);
t=new Thread (this, try
name); S.O.P(“New {
Thread”); t.start(); Thread.sleep(10000);
}
}catch(InterruptedException
e)
public void run() { S.O.P(“Main Thread
{ Interrupted”);}
try
{ // some loop}catch(){ } S.O.P(“Main Thread Exiting”);
}
S.O.P(name +
}
“existing”);
}
}
Example (isAlive(), join())
Class NT implements Runnable Class Demo
{ {
String name; Thread t; P.S.V.M(--)
{
NT (String tname) NT one=new NT(“One”);
{ NT two=new NT(“Two”);
name=tname; NT three=new NT(“Three”);
t=new Thread (this, S.O.P(“Thread one is
name); S.O.P(“New Alive:”,one.t.isAlive();
Thread”); t.start(); try
} {
S.O.P(“Waiting for the Threads to Finish:”);
public void run() one.t.join();
{ two.t.join();
try three.t.join();
{ // some loop}catch(){ } }catch(InterruptedException e)
S.O.P(name + { S.O.P(“Main Thread Interrupted”);}
“existing”); S.O.P(“Main Thread Exiting”);
} }
} }

UNIT-III Multithreading
Thread Priorities
 Every thread is assigned a priority (between 1 and 10).
 The default is 5.
 The higher the number, the higher the priority.
 Can be set wit h setPriorit y( nt aPriority)
i .

 The standard mode of operation is that the scheduler


executes threads with higher priorities first.
 This simple scheduling algorithm can cause problems.
Specifically, one high priority thread can become a "CPU hog".
 A thread using vast amounts of CPU can share CPU time with
other threads by invoking the yield() method on itself.
Thread Priorities

 Most OS do not employ a scheduling algorithm


as simple as this one.
 Most modern OS have thread aging.
 The more CPU a thread receives, the lower its
priority becomes.
 The more a thread waits for the CPU, the higher its
priority becomes.
 Because of thread aging, the effect of setting a
thread's priority is dependent on the platform.
Example

UNIT-III g
Example (CreatingMultiple Threads)
class Clicker implements Runnable Class Demo
{ {
int click; Thread t; P.S.V.M(--)
private volatile Boolean rumming=true; {
Clicker (int p) Thread.currentThread().setPriority(10)
{ ; Clicker hi=new Clicker
t=new Thread (this); (Thread.NORM_PRIORITY+2);
t.setPriority(p); Clicker lo= new Clicker (3);
} lo.start();
public void run() hi.start();
{ try
while(rumming){ click++;} { Thread.sleep(10000);
} }catch() { }
lo.stop();
Public void stop() hi.stop();
{ running=false;} try{ hi.t.join();
lo.t.join();
Public void start() }catch() {}
{ t.start();} S.O.P(“Low Thread” + lo.click);
S.O.P(“High Thread” + hi.click);
}
}
}
Concurrent Access to Data
 Those familiar with databases will understand
that concurrent access to data can lead to data
integrity problems.
 Specifically, if two sources attempt to update

the same data at the same time, the result of


the data can be undefined.
 The outcome is determined by how the
scheduler schedules the two sources.
 Since the schedulers activities cannot be predicted,
the outcome cannot be predicted
Concurrent Access to Data

 Databases deal with this mechanism through


"locking“.
 If a source is going to update a table or record, it can
lock the table or record until such time that the data
has been successfully updated.
 While locked, all access is blocked except to the
source which holds the lock.

 Java has the equivalent mechanism. It is called


synchronization.
 Java has a keyword calle d synchronized.

You might also like