You are on page 1of 30

Multi Threaded

Programming

Megha Aggarwal
IGIT, GGSIP University,
Delhi Email :
What is a Thread ?
• A form of multi tasking.
•A single sequential flow of control
• A piece of code that can execute in concurrence with
other threads.
• All programs have at least one thread – the main thread
• And these are independent executables.
• All threads are parts of a process hence communication
easier and simpler.
• A thread can belong to a thread group.
TYPES OF MULTI-TASKING
1. Process based
2. Thread based

Single Task:
Two Task:
Serial Vs. Parallel Computing

COUNTER COUNTER 2

COUNTER 1

Q
Please
Thread Vs. Process

 The difference : Threads share memory


space, Processes don’t.
 Threads are cheaper to create – no need to
copy memory
 Communication between threads is faster –
shares memory
 Communication must be done carefully to
avoid memory conflict and timing problems
Thread Resources
 Each thread has its own:

1. Program counter (Point of execution)


2. Control stack (Procedural call/ return)
3. Data Stack (Local variables)

 And All threads in a program share:


1. Program code
2. The heap (objects)
3. Class and instance variables
Creating a thread
Two ways to define a Thread:
1. Extending Thread class
2. Implementing Runnable interface

To start a Thread:
1. Create Thread Object
2. Call its start() method
Method 1 : Subclassing Thread
Create a separate subclass that extends Thread.
- No import statement needed. Thread is in java.lang package

Put the actions to be performed in the run() method


of subclass.
- public void run() {…}
- It defines the starting point for JVM

Create an instance of Thread subclass.


- NewThread ob=new NewThread();

Call that instance’s start( ) to begin execution of the


new thread.
- ob.start();
Example :
class NewThread extends Thread {
NewThread() {
super("Demo Thread");
start(); // Start the thread
}

public void run()


{ ... }
}
class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
...
...
}
Method 2 : Implementing Runnable
Put the actions to be performed in the run() method
of your existing class.
- public void run() {…}

Have a class that implements Runnable interface.


- No import statement needed. Thread is in java.lang package
- A class can implement multiple interface

Construct an instance of Thread passing in existing


object (ie, Runnable).
- Thread ob = new Thread(theRunnableObject);

Call Thread’s start( ) method to begin execution of


the new thread.
- ob.start();
Example :
class ThreadClass implements Runnable {

public void run()


{ // thread actions here
// to access thread instance here, use
// Thread.currentThread();
...
}
Public void startThread()
{
Thread t =new Thread(this);
t.start(); // calls run() method
}
...
}
Which approach is Better ??
Ans : Implementing Runnable Thread

Reasons :
Not a big problem for getting started but a bad
habit for industrial strength development

The methods of the worker class and the Thread


class get all tangled up

Makes it hard to migrate to Thread Pools and other


more efficient approaches
Thread Priorities And Preemption
 A thread’s default priority is same as the creating
thread
 Thread API defines three final static variables for
thread priorities.
Thread.MIN_PRIORITY (1)
Thread.NORM_PRIORITY (5)
Thread.MAX_PRIORITY (10)
 We can obtain the current priority by the method:
final int getPriority( )
 To set new priority, use the setPriority( ) method
Thread class.
final void setPriority(int level)
Here, level specifies the new priority setting for the
calling thread.
PROBLEMS
 Starvation can occur for lower – priority threads if the
higher – priority threads never terminates, sleeps, or
wait for I/O

PREEMPTION

yield () Method
 Allows any other threads of same or higher
priority to execute (moves itself to the end of
priority queue)
 If all waiting threads have a lower prioritiy, then
the yielding thread remains on the CPU.
Thread Life Cycle Diagram:
Class Thread and its Methods

Constructors :
Thread () 
           - Allocates a new Thread object.

Thread (Runnable target) 
          -  Allocates a new Thread object.

Thread (Runnable target, String name) 
           - Allocates a new Thread object.

Thread (String name) 
           - Allocates a new Thread object.
A few Methods
 static   int activeCount() 
           Returns the number of active threads in the current thread's thread
group.
 static   Thread currentThread() 
           Returns a reference to the currently executing thread object.
 void destroy() 
           Destroys this thread, without any cleanup.
 static  int enumerate(Thread[] tarray) 
           Copies into the specified array every active thread in the current
thread's thread group and its subgroups.
 String getName() 
          Returns this thread's name.
 int getPriority() 
           Returns this thread's priority.
 ThreadGroup getThreadGroup() 
           Returns the thread group to which this thread belongs.
A few Methods (…contd)
 void interrupt() 
           Interrupts this thread.
 boolean isAlive() 
           Tests if this thread is alive.
 boolean isInterrupted() 
           Tests whether this thread has been interrupted.
 void join () 
           Waits for this thread to die.
 void join (long millis) 
           Waits at most millis milliseconds for this thread to die.
 void run() 
           If this thread was constructed using a separate Runnable run object,
then that Runnable object's run method is called; otherwise, this method
does nothing and returns.
 void setName(String name) 
           Changes the name of this thread to be equal to the argument name.
A few Methods (…contd)
 void setPriority(int newPriority) 
Changes the priority of this thread.
 static void sleep(long millis) 
           Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds.
 void start() 
           Causes this thread to begin execution; the Java Virtual Machine calls
the run method of this thread.
 String toString() 
           Returns a string representation of this thread, including the thread's
name, priority, and thread group.
 static void yield() 
           Causes the currently executing thread object to temporarily pause and
allow other threads to execute.
Daemon Threads
• Any Java thread can be a daemon thread.
• Daemon threads are service providers for other
threads running in the same process.
• The run() method for a daemon thread is typically an
infinite loop that waits for a service request.
• When the only remaining threads in a process are
daemon threads, the interpreter exits.
• To specify that a thread is a daemon thread, call
the setDaemon() method with the argument true. To
determine if a thread is a daemon thread, use the
method isDaemon().
Pitfalls of Thread Programming:

More than one thread can be changing memory at


the same time.
Threads execute in nondeterministic order.
Bugs show up rarely and the threads may be hard
to repeat.
If two threads access the same memory location,
they can conflict with each other.
The resulting state may be unexpected and wrong
sometimes.
Threaded programs are hard to code and even
harder to debug
The JAVA Monitor Model
Method 1

Method 2

Key
Block 1

Threads
Synchronization in Monitors

• Every object has an intrinsic lock associated with


it.
• A thread that needs exclusive and consistent
access to an object's fields has to acquire the
object's intrinsic lock before accessing them.
• It releases the intrinsic lock when it's done with
them.
Ways for synchronization

Synchronized Methods Synchronized Block


public class SynchronizedCounter { public void addName(String s)
private int c = 0;
public synchronized void increment() { synchronized (this)
{ {
c++;
} lastName = s;
public synchronized void decrement() nameCount++;
{ }
c--;
} nameList.add(s);
public synchronized int value() { }
return c;
}
}
Synchronized Methods
Once a Thread is inside Synchronized method, All
other threads trying to call it on same instance have to
wait

When thread returns from the method, other threads


can call it on same instance.

Once a thread acquires the lock on an object, no


other thread can enter any of the synchronized
methods in that class for that object.

Only methods can be synchronized, not variables.


Synchronized Block

We can reduce the scope of the synchronized part to


something less than a full method—to just a block.

Here, we specify which object’s lock we want to use as


the lock

We can use some third-party object as the lock for this


piece of code.
Dead Lock
• It occurs when two threads have a circular
dependency on a pair of synchronized objects.
• When threads can’t make progress because they are
waiting for each other.
• It can happen with at least two threads and two
mutexes (locks).

DeadLocks is difficult to debug because :


• Occurs rarely
• May involve more than two threads and two
synchronised objects
Example for Deadlock
Static long totalBalance (Account x, Account y) {
synchronized (x) {
synchronized (y) {
long total = x.getBalance();
total+= y.getBalance();
return total;
}
}}
Thread 1 Thread 2
Begins totalBalance(a1,a2) Begins totalBalance(a2,a1)
Locks a1’s mutex Locks a2’s mutex
Blocks trying to access a2’s Blocks trying to access a1’s
mutex mutex
Thank You

You might also like