0% found this document useful (0 votes)
29 views47 pages

Multi Threaded Programming

Thread-based multitasking allows a single program to execute multiple tasks concurrently using threads. Threads are lightweight tasks that share the same memory space and process. Context switching and communication between threads has low overhead. When a Java program starts, a main thread is automatically created to execute the program. Additional child threads can be created to perform concurrent tasks and the main thread must typically finish last.

Uploaded by

avav
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)
29 views47 pages

Multi Threaded Programming

Thread-based multitasking allows a single program to execute multiple tasks concurrently using threads. Threads are lightweight tasks that share the same memory space and process. Context switching and communication between threads has low overhead. When a Java program starts, a main thread is automatically created to execute the program. Additional child threads can be created to perform concurrent tasks and the main thread must typically finish last.

Uploaded by

avav
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/ 47

Multithreaded Programming

Thread-Based Multi-Tasking
• Thread-based multi-tasking is about a single program
executing concurrently several tasks e.g. a text editor
printing and spell-checking text.
• Threads are lightweight tasks:
1) they share the same address space
2) they cooperatively share the same process
3) inter-thread communication is inexpensive
4) context-switching from one thread to another is
low-cost
• Java multi-tasking is thread-based.
Reasons for Multi-Threading
• Multitasking threads require less overhead than multitasking
processes. Processes are heavyweight tasks that require their
own separate address spaces.
• Interprocess communication is expensive and limited. Context
switching from one process to another is also costly.
• Threads, on the other hand, are lighter weight. They share the
same address space and cooperatively share the same
heavyweight process. Interthread communication is
inexpensive, and context switching from one thread to the next
is lower in cost.
• While Java programs make use of process-based multitasking
environments, process-based multitasking is not under Java’s
control. However, multithreaded multitasking is.
Thread Lifecycle
• Thread exists in several states:
1) ready to run
2) running
3) a running thread can be suspended
4) a suspended thread can be resumed
5) a thread can be blocked when waiting for a resource
6) a thread can be terminated
• Once terminated, a thread cannot be resumed.
Thread Lifecycle
sleep(500)
Active

wake up
JVM
Born start() suspend()

resume()

Runnable
Blocked
stop() wait
stop()
notify

block on I/O
Dead I/O available
Thread Lifecycle
• New state – After the creations of Thread instance the thread is in this
state but before the start() method invocation. At this point, the thread
is considered not alive.
• Runnable (Ready-to-run) state – A thread start its life from Runnable
state. A thread first enters runnable state after the invoking of start()
method but a thread can return to this state after either running,
waiting, sleeping or coming back from blocked state also. On this state a
thread is waiting for a turn on the processor.
• Running state – A thread is in running state that means the thread is
currently executing. There are several ways to enter in Runnable state
but there is only one way to enter in Running state: the scheduler select
a thread from runnable pool.
• Dead state – A thread can be considered dead when its run() method
completes. If any thread comes on this state that means it cannot ever
run again.
• Blocked - A thread can enter in this state because of waiting the
resources that are hold by another thread.
CREATING THREAD
Creating a Thread
• In the most general sense, you create a thread
by instantiating an object of type Thread.
• Java defines two ways in which this can be
accomplished:
– You can implement the Runnable interface.
– You can extend the Thread class, itself.
Implementing Runnable
• The easiest way to create a thread is to create a
class that implements the Runnable interface.
Runnable abstracts a unit of executable code.
• You can construct a thread on any object that
implements Runnable.
• To implement Runnable, a class need only
implement a single method called run( ), which is
declared like this:
public void run( )
• Inside run( ), you will define the code that
constitutes the new thread. It is important to
understand that run( ) can call other methods,
use other classes, and declare variables, just
like the main thread can.
• The only difference is that run( ) establishes
the entry point for another, concurrent thread
of execution within your program. This thread
will end when run( ) returns.
• After you create a class that implements Runnable,
you will instantiate an object of type Thread from
within that class.
• Thread defines several constructors. The one that
we will use is shown here:
Thread(Runnable threadOb, String threadName)
• After the new thread is created, it will not start running until
you call its start( ) method, which is declared within Thread.
• In essence, start( ) executes a call to run( ).
// Create a second thread.
class NewThread implements Runnable {
Thread t;

NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}

// This is the entry point for the second thread.


public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread

try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
• Inside NewThread’s constructor, a new Thread
object is created by the following statement:
t = new Thread(this, "Demo Thread");
• Passing this as the first argument indicates that you want
the new thread to call the run( ) method on this object.
• Next, start( ) is called, which starts the thread of
execution beginning at the run( ) method. This causes
the child thread’s for loop to begin.
• After calling start( ), NewThread’s constructor returns to
main( ).
• When the main thread resumes, it enters its for loop.
Both threads continue running, sharing the CPU in single
core systems, until their loops finish.
• The output produced by this program is as
follows. (Your output may vary based upon the
specific execution environment.)
Thread Class Methods

• Start: a thread by calling start its run method


• Sleep: suspend a thread for a period of time
• Run: entry-point for a thread
• Join: wait for a thread to terminate
• isAlive: determine if a thread is still running
• getPriority: obtain a thread’s priority
• getName: obtain a thread’s name
New Thread: By Implementing Runnable
Interface
New Thread: Runnable
To create a new thread by implementing the Runnable
interface:
1) create a class that implements the run method (inside this
method, we define the code that constitutes the new
thread):
public void run()
2) instantiate a Thread object within that class, a possible
constructor is:
Thread(Runnable threadOb, String threadName)
3) call the start method on this object (start calls run):
void start()
Example: New Thread 1(using Runnable)

• A class NewThread that implements Runnable:


class NewThread implements Runnable {
Thread t;
//Creating and starting a new thread. Passing this to the Thread
constructor – the new thread will call this object’s run method:
NewThread() {
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start();
}
New Thread: By Extending Thread class
New Thread: By Extending Thread class
• There are two steps:
1. create a new class that extends Thread and
override run( ) method available in Thread
class. This method provides an entry point
for the thread and you will put your
complete business logic inside this method.
2. Create Thread object and you can start it by
calling start() method, which executes a call
to run( ) method.
Example 1
Example 2
Example 3
Example 3
Example 3
THE MAIN THREAD
The Main Thread
• When a Java program starts up, one thread begins
running immediately. This is usually called the main
thread of your program, because it is the one that is
executed when your program begins. The main
thread is important for two reasons:
• It is the thread from which other “child” threads will
be spawned.
• Often, it must be the last thread to finish execution
because it performs various shutdown actions.
The Main Thread
• Although the main thread is created automatically when your
program is started, it can be controlled through a Thread object.
• To do so, you must obtain a reference to it by calling the method
currentThread( ), which is a public static member of Thread.
• Its general form is shown here:
static Thread currentThread( )
• This method returns a reference to the thread in which it is
called.
• Once you have a reference to the main thread, you can control it
just like any other thread.
• In this program, a reference to the current thread (the main
thread, in this case) is obtained by calling currentThread( ), and
this reference is stored in the local variable t.
• Next, the program displays information about the thread. The
program then calls setName( ) to change the internal name of
the thread.
• Information about the thread is then redisplayed. Next, a loop
counts down from five, pausing one second between each line.
• The pause is accomplished by the sleep( ) method. The argument
to sleep( ) specifies the delay period in milliseconds.
• Notice the try/catch block around this loop. The sleep( ) method
in Thread might throw an InterruptedException.
• This would happen if some other thread wanted to interrupt this
sleeping one.
• Here is the output generated by this program:
Thread Priorities
Thread Priorities
• Thread priorities are used by the thread
scheduler to decide when each thread should
be allowed to run.
• To set a thread’s priority, use the setPriority( )
method, which is a member of Thread. This is
its general form:
final void setPriority(int level)
SYNCHRONIZATION
Synchronization
• 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.
• Key to synchronization is the concept of the monitor. A monitor is an
object that is used as a mutually exclusive lock. Only one thread can
own a monitor at a given time.
• When a thread acquires a lock, it is said to have entered the
monitor. All other threads attempting to enter the locked monitor
will be suspended until the first thread exits the monitor.
• These other threads are said to be waiting for the monitor. A thread
that owns a monitor can reenter the same monitor if it so desires.
Threads: Synchronization
• How to prevent two threads from
simultaneously writing and reading the same
object?
• Java implementation of monitors:
1) classes can define so-called synchronized
methods
2) each object has its own implicit monitor
that is automatically entered when one of the
object’s synchronized methods is called
3) once a thread is inside a synchronized
method, no other thread can call any other
synchronized method on the same object
Thread Synchronization

• Language keyword: synchronized


• Takes out a monitor lock on an object
– Exclusive lock for that thread
• If lock is currently unavailable, thread will be
blocked
Thread Synchronization

• Protects access to code, not to data


– Make data members private
– Synchronize accessor methods
• Puts a “force field” around the locked object
so no other threads can enter
• Actually, it only blocks access to other synchronizing
threads
Interthread Communication
Interthread Communication
• The preceding examples unconditionally
blocked other threads from asynchronous
access to certain methods.
• This use of the implicit monitors in Java
objects is powerful, but you can achieve a
more subtle level of control through
interprocess communication.
Interthread Communication
• Java includes an elegant interprocess communication
mechanism via the wait( ), notify( ), and notifyAll( ) methods
• Let’s now work through an example that uses wait( ) and
notify( ). To begin, consider the following sample program
that incorrectly implements a simple form of the
producer/consumer problem. It consists of four classes: Q,
the queue that you’re trying to synchronize; Producer, the
threaded object that is producing queue entries; Consumer,
the threaded object that is consuming queue entries; and PC,
the tiny class that creates the single Q, Producer, and
Consumer.
// An incorrect implementation of a producer and consumer.
class Q {
int n;

synchronized int get() {


System.out.println("Got: " + n);
return n;
}

synchronized void put(int n) {


this.n = n;
System.out.println("Put: " + n);
}
}

class Producer implements Runnable {


Q q;

Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}

public void run() {


int i = 0;

while(true) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q;

Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}

public void run() {


while(true) {
q.get();
}
}
}

class PC {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);

System.out.println("Press Control-C to stop.");


}
}
Why Threading
• All threads are objects. Therefore, if you want to run 10 threads, then
you have to create 10 objects (either of similar class or of different
classes).
• Q. agar normally hum kisi class ke 10 objects bna de to wo bhi to
thread ki tarah hi kaam karenge.
• A. Concept of threading provides parallel execution of more than one
tasks. You can create 10 objects without multithreading concept but
you cannot force them to run in parallel. Whereas, with
multithreading, you can do it.
– Advantage of thread is that whenever a thread is sleeping, execution control
goes to some other thread. It does not wait for the thread to be awaken.
Whereas in normal execution it waits.
• If you want to see the benefits of multithreading, take an example
where it is really required.
• ‘Thread.sleep()’ can be used in any place in a class; it does not matter
whether that class inherits Thread class or not.

You might also like