0% found this document useful (0 votes)
15 views

Multi Threading

Uploaded by

VIJAY ANAND
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Multi Threading

Uploaded by

VIJAY ANAND
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Multithreading and Generic

Programming
What is Multitasking?

More than one program gets executed simultaneously. Multitasking is a timesharing

process. CPU switches from one program to another so quickly to complete all the

programs simultaneously. Since each program occupies different memory location,

multitasking is called as heavy weight process.


What is Multithreading?

More than one part of program called threads is executed simultaneously. Multithreading

is also timesharing process. CPU switches from one activity to another activity within the

program so quickly to complete all activities simultaneously. Multithreading is a light

weight process because the activities/threads share the same memory location.
Difference between multitasking and multithreading:

S.NO MULTITASKING MULTITHREADING

While in multithreading, many threads are created


In multitasking, users are allowed to
1. from a process through which computer power is
perform many tasks by CPU.
increased.

Multitasking involves often CPU While in multithreading also, CPU switching is


2.
switching between the tasks. often involved between the threads.

In multitasking, the processes share While in multithreading, processes are allocated


3.
separate memory. same memory.
Difference between multitasking and multithreading:

In multitasking, CPU is provided in While in multithreading also, CPU is provided in


5. order to execute many tasks at a order to execute many threads from a process
time. at a time.

In multitasking, processes don’t


While in multithreading, each process share
6. share same resources, each process
same resources.
is allocated separate resources.

Multitasking is slow compared to


7. While multithreading is faster.
multithreading.

In multitasking, termination of While in multithreading, termination of thread


8.
process takes more time. takes less time.
Thread Life Cycle

A thread can be in one of the five states. A thread goes through various stages in its life
cycle. For example, a thread is born, started, runs, and then dies.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
Thread Life Cycle
Thread Life Cycle

NEW – a newly created thread that has not yet started the execution

RUNNABLE – either running or ready for execution but it's waiting for resource allocation

BLOCKED – waiting to acquire a monitor lock to enter or re-enter a synchronized

block/method

WAITING – waiting for some other thread to perform a particular action without any time

limit

TIMED_WAITING – waiting for some other thread to perform a specific action for a

specified period

TERMINATED – has completed its execution


Thread Life Cycle

New
A NEW Thread (or a Born Thread) is a thread that's been created but not yet started. It
remains in this state until we start it using the start() method.

The following code snippet shows a newly created thread that's in the NEW state:

class Demo_New extends Thread{


//public void run(){
//System.out.println("thread is running...");
//}
public static void main(String args[]){
Demo_New t1=new Demo_New();
//t1.start();
System.out.print(t1.getState());}
}
NEW
Thread Lify Cycle

Runnable
When we've created a new thread and called the start() method on that, it's moved
from NEW to RUNNABLE state. Threads in this state are either running or ready to run,
but they're waiting for resource allocation from the system.
In a multi-threaded environment, the Thread-Scheduler (which is part of JVM) allocates a
fixed amount of time to each thread. So it runs for a particular amount of time, then
relinquishes the control to other RUNNABLE threads.
Thread Life Cycle

class Demo_Runnable extends Thread{


//public void run(){
//System.out.println("thread is running...");
//}
public static void main(String args[]){
Demo_Runnable t1=new Demo_Runnable();
t1.start();
System.out.print(t1.getState());}
}

Output:

Runnable
Thread Life Cycle

Blocked
A thread is in the BLOCKED state when it's currently not eligible to run. It enters this state
when it is waiting for a monitor lock and is trying to access a section of code that is
locked by some other thread.

public class Demo_Blocked {


public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new DemoThreadB());
Thread t2 = new Thread(new DemoThreadB());
t1.start();
t2.start();
Thread.sleep(1000);
System.out.print(t2.getState());
System.exit(0);
}
}
Thread Life Cycle
class DemoThreadB implements Runnable {
@Override
public void run() {
commonResource();
}

public static synchronized void commonResource() {


while(true) {
// Infinite loop to mimic heavy processing
// 't1' won't leave this method
// when 't2' try to enter this
}
}
}

Output:
Blocked
Thread Life Cycle
In this code:

We've created two different threads – t1 and t2


t1 starts and enters the synchronized commonResource() method; this means that only
one thread can access it; all other subsequent threads that try to access this method will
be blocked from the further execution until the current one will finish the processing
When t1 enters this method, it is kept in an infinite while loop; this is just to imitate
heavy processing so that all other threads cannot enter this method
Now when we start t2, it tries to enter the commonResource() method, which is already
being accessed by t1, thus, t2 will be kept in the BLOCKED state
Thread Life Cycle

Waiting
A thread is in WAITING state when it's waiting for some other thread to perform a
particular action. According to JavaDocs, any thread can enter this state by calling any
one of the following three methods:
object.wait()
thread.join() or
LockSupport.park()
Note that in wait() and join() – we do not define any timeout period as that scenario is
covered in the next section.
Creating Threads
How to create thread
There are two ways to create a thread:

1. By extending Thread class

2. By implementing Runnable interface.

Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
Creating Threads
1) Java Thread Example by extending Thread class
class Create_Thread extends Thread
{
public void run()
{
System.out.println("concurrent thread started running..");
}
}

class Demo
{
public static void main(String args[])
{
Create_Thread mt = new Create_Thread();
mt.start();
}
}
Output:
concurrent thread started running..
Creating Threads

Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named
run().
public void run(): is used to perform action for a thread.
Creating Threads
class MyThread implements Runnable
{
public void run()
{
System.out.println("concurrent thread started running..");
}
}

class MyThreadDemo
{
public static void main(String args[])
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}
Output:
concurrent thread started running..
Thread Methods
Commonly used methods of Thread class:

public void run(): is used to perform action for a thread.


public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.
Thread Methods
Commonly used methods of Thread class:

public int getId(): returns the id of the thread.


public Thread.State getState(): returns the state of the thread.
public boolean isAlive(): tests if the thread is alive.
public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public void interrupt(): interrupts the thread.
public boolean isInterrupted(): tests if the thread has been interrupted.
public static boolean interrupted(): tests if the current thread has been interrupted.
Thread Methods
Advantages and disadvantages of threads in java

Reduces development time.

Reduces maintenance costs.

Improves the performance of complex applications.

Useful for improving the responsiveness of the user interfaces.

Used in server applications for improving high throughput and resource utilization.

Parallelize tasks.
Priority of a Thread (Thread Priority):

Each thread have a priority. Priorities are represented by a number between 1 and 10. In

most cases, thread schedular schedules the threads according to their priority .

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Get and Set Thread Priority:


public final int getPriority(): java.lang.Thread.getPriority() method returns priority of
given thread.
public final void setPriority(int newPriority): java.lang.Thread.setPriority() method
changes the priority of thread to the value newPriority. This method throws
IllegalArgumentException if value of parameter newPriority goes beyond minimum(1) and
maximum(10) limit.
Synchronizing Threads

When we start two or more threads within a program, there may be a situation when
multiple threads try to access the same resource and finally they can produce unforeseen
result due to concurrency issues. For example, if multiple threads try to write within a
same file then they may corrupt the data because one of the threads can override data or
while one thread is opening the same file at the same time another thread might be
closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only
one thread can access the resource at a given point in time. This is implemented using a
concept called monitors. Each object in Java is associated with a monitor, which a thread
can lock or unlock. Only one thread at a time may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized blocks. You keep shared resources within
this block. Following is the general form of the synchronized statement −
Synchronizing Threads

synchronized(objectidentifier) {
// Access shared variables and other shared
resources
}
Inter-thread Communication

If you are aware of interprocess communication then it will be easy for you to understand
interthread communication. Interthread communication is important when you develop
an application where two or more threads exchange some information. Inter-thread
communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed.It is implemented by following methods of Object class:

1. wait()

2. notify()

3. notifyAll()
Inter-thread Communication

 When we apply wait() method on current running thread release the monitor and go

to sleep until another thread doesn’t call notify() with same object monitor.

 notify()-this method wake up thread which is waiting for object monitor.

 notifyall()-wake up all thread of that called wait() on same object.


Threading

What is thread?
Difference between multitasking and multithreading.
Thread lifecycle
Thread methods
Ways to create thread in java
Synchronized threads
Inter-thread communication.

You might also like