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

Multithreading in Java

Multithreading in java

Uploaded by

Solaim Faisal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Multithreading in Java

Multithreading in java

Uploaded by

Solaim Faisal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Multithreading in Java

Anupama Mishra
Multithreading
Tasks:
There are two types of Executing the tasks:

1. Single Tasking: Executing only one task at a time is called single


tasking. In single tasking the microprocessor will be sitting idle for
most of the time. This means micro processor time is wasted.

2. Multi tasking: Executing more than one task at a time is called multi
tasking.

Multitasking is divided into two types:

Process Based Multitasking: Executing several programs simultaneously


is called process based multi tasking.

Thread Based Multitasking: Executing different parts of the same


program simultaneously with the help of a thread is called thread based
multitasking. Anupama Mishra
Multithreading
Java provides built-in support for multithreaded programming.

 A multithreaded program contains two or more parts that can run


concurrently.

Multiprocessing and multithreading, both are used to achieve


multitasking.

Multithreading are used in designing server-side programs to handle


multiple clients at a time.

Java Multithreading is mostly used in games, animation etc.

Anupama Mishra
Thread:
•Thread is a smallest unit of code.

•Thread is also defined as a subprocess.



•A Thread sometimes called an execution context or a light weight
process.

Advantage of Multithreading:

• It doesn't block the user.

• can perform many operations together so it saves time.

• Threads are independent so it doesn't affect other threads.

Anupama Mishra
Multithreading
Life cycle of a thread:

1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state

Anupama Mishra
Multithreading
Thread Life Cycle

Anupama Mishra
Multithreading
1.New (Newborn State):

When we create a thread object using Thread class, thread is born and is
known to be in Newborn state. That is, when a thread is born, it enters into
new state but the start() method has not been called yet on the instance.

2.Runnable state:

•Runnable state means a thread is ready for execution. When the start()
method is called on a new thread, thread enters into a runnable state.

•In runnable state, thread is ready for execution and is waiting for
availability of the processor (CPU time). That is, thread has joined queue
(line) of threads that are waiting for execution.

•The process of allocating time to threads is known as time slicing.

Anupama Mishra
Multithreading

Anupama Mishra
Multithreading
3.Running state:

•Running means Processor (CPU) has allocated time slot to thread for
its execution. When thread scheduler selects a thread from the runnable
state for execution.

•In running state, processor gives its time to the thread for execution and
executes its run() method.

•A thread can come into running state only from runnable state.

Anupama Mishra
Multithreading
Running state:
A running thread may give up the following situations and can enter
into the Blocked state:
1. When sleep() method is invoked on a thread to sleep for specified time
period.

2. When a thread is suspended using suspend() method for some time in


order to satisfy some conditions. A suspended thread can be revived by
using resume() method.

3. When wait() method is called on a thread to wait for some time. The
thread in wait state can be run again using notify() or notifyAll()
method.

Anupama Mishra
Multithreading

4.Blocked state:

A thread is considered to be in the blocked state when it is suspended,


sleeping, or waiting for some time in order to satisfy some condition.

5.Dead state:

A thread dies or moves into dead state automatically when its run()
method completes the execution of statements. That is, a thread is
terminated or dead when a thread comes out of run() method. A thread
can also be dead when the stop() method is called.

Anupama Mishra
Multithreading
Creation of a thread
1. By Extending Thread class:

The first way to create a thread is to create a new class that extends the
Thread class and then to create an instance of this class. The class must
override the run() method which is the entry point for the new thread.

2. By Implementing Runnable Interface:


• Define a class that implements Runnable interface.

• The Runnable interface has only one method, run(), that is to be


defined in the method with the code to be executed by the thread.

Anupama Mishra
Multithreading
1.By Extending the Thread class
• Threads are implemented as objects that contains a method called run()
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
• Create a thread:
MyThread thr1 = new MyThread();

• Start Execution of threads:


thr1.start();

• Create and Execute:


new MyThread().start();
Anupama Mishra
Extending the thread class :
Example:
class MyThread extends Thread // Extending thread class
{
public void run() // run() method declared
{
System.out.println(" this thread is running ... ");
}
}
class ThreadEx
{
public static void main(String [] args )
{
MyThread t = new MyThread();
t.start(); // run() method called through start()
//run(). start() is a method in Thread class.
}
}
Anupama Mishra
Multithreading
2.By Implementing the Runnable interface
class MyThread implements Runnable
{
public void run()
{
// thread body of execution
}
}
• Creating Object:
MyThread myObject = new MyThread();

• Creating Thread Object:


Thread thr1 = new Thread( myObject );

• Start Execution: Anupama Mishra


thr1.start();
Multithreading
Implementing the runnable interface : example
class MyThread implements Runnable // Implementing Runnable interface
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
MyThread t=new MyThread(); // object initiated for class
Thread t1 =new Thread(t); // object initiated for thread
t1.start();
}
}

Anupama Mishra
Multithreading
Three threads example
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("\t From ThreadA: i= "+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("\t From ThreadB: j= "+j);
}
System.out.println("Exit from B");
}
} Anupama Mishra
Three threads example:
class C extends Thread
{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println("\t From ThreadC: k= "+k);
}
System.out.println("Exit from C");
}
}
class ThreadTest
{
public static void main(String args[])
{
new A().start();
new B().start();
new C().start();
}
}
Anupama Mishra
Three threads example: Run 1

Anupama Mishra
Three threads example: Run 2

Anupama Mishra
Multithreading
Thread class methods
• start() Starts execution of the thread.
• stop() Terminates the current thread.
• suspend() Suspends the thread.
• resume() Restarts the suspended thread.
• sleep() This method suspends execution of the executing thread for the
specified number of milliseconds. It can throw an interrupted Exception.

• getName() Obtains a thread name.


• getPriority() Obtain a thread‟s priority.
• getState() Returns the state of the thread
• isalive() Determine if a thread is still running.
• wait() Waits for a thread to terminate.
• run() Entry point for the Thread.
Anupama Mishra
Multithreading
Using different methods of Thread class
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
if(i==1) yield();
System.out.println("\t From ThreadA: i= "+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("\t From ThreadB: j= "+j);
if(j==2) stop();
}
System.out.println("Exit from B");
}
} Anupama Mishra
class C extends Thread
{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println("\t From ThreadC: k= "+k);
if(k==2)
try
{
sleep(1000);
}
catch(Exception e)
{ }
}
System.out.println("Exit from C");
}
}
class ThreadMethod
{
public static void main(String args[])
{
new A().start();
new B().start();
new C().start();
}
} Anupama Mishra
Anupama Mishra
Multithreading
Thread priorities

• Thread priorities are integers that specify the relative priority of one
thread to another.

• Higher priority thread doesn't run any faster than a lower priority thread.
• Instead a thread‟s priority is used to decide when to switch from one
running thread to the next. This is called as context switch.

• A threadcan have a maximum priority of 10 and a minimum of 1.


Normal Priority is 5.

Anupama Mishra
Multithreading
Thread priorities

• In Java, each thread is assigned priority, which affects the order in


which it is scheduled for running. The default priority
(NORM_PRIORITY) of threads and they are served using FCFS
policy.

– Java allows users to change priority:

• ThreadName.setPriority(intNumber)
– MIN_PRIORITY = 1
– NORM_PRIORITY=5
– MAX_PRIORITY=10

Anupama Mishra
Thread priorities Example:
public class A implements Runnable
{
public void run() {
System.out.println(Thread.currentThread());
}
public static void main(String[] args) {
A a = new A();
Thread t = new Thread(a, "NewThread");
System.out.println("Priority of Thread: " +t.getPriority());
System.out.println("Name of Thread: " +t.getName());
t.start();
}
} Anupama Mishra
Multithreading
Thread priorities
class A extends Thread
{
public void run()
{
System.out.println("Thread A started");
for(int i=1;i<=4;i++)
{
System.out.println("\t From ThreadA: i= "+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
System.out.println("Thread B started");
for(int j=1;j<=4;j++)
{
System.out.println("\t From ThreadB: j= "+j);
}
System.out.println("Exit from B");
}
Anupama Mishra
}
Thread priorities
class C extends Thread
{
public void run()
{
System.out.println("Thread C started");
for(int k=1;k<=4;k++)
{
System.out.println("\t From ThreadC: k= "+k);
}
System.out.println("Exit from C"); } }
class ThreadPriority
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority()+1);
threadA.setPriority(Thread.MIN_PRIORITY);
System.out.println("Started Thread A");
threadA.start();
System.out.println("Started Thread B");
threadB.start();
System.out.println("Started Thread C");
threadC.start();
System.out.println("End of main thread");
}
} Anupama Mishra
Multithreading
Thread synchronization

•When a thread is already accessing an instance of a class, preventing any


other thread from acting on the same instance is called „thread
synchronization in Java’.

•The object on which threads are synchronized is called synchronized


object.

•For Example: One thread may try to read a record from a file while
another is still writing to the same file.

•Java provides a keyword named “synchronized” that helps to


synchronize thread.

Anupama Mishra
Thread synchronization

• The purpose (objective) of thread synchronization:


1.Two or more threads accessing the same data simultaneously may lead to
loss of data integrity. In order to avoid this java uses the concept of
monitor. A monitor is an object used as a mutually exclusive lock.

2. At a time only one thread can access the Monitor. A second thread
cannot enter the monitor until the first comes out. Till such time the other
thread is said to be waiting.

3.The keyword Synchronized is used in the code to enable synchronization


and it can be used along with a method.

Anupama Mishra
Thread synchronization

Anupama Mishra
Thread synchronization

• Applications Access to Shared Resources need to be coordinated.


– Printer (two jobs cannot be printed at the same time)
– Simultaneous operations on your bank account.
– Can the following operations be done at the same time on the same
account?
• Deposit()
• Withdraw()
• Enquire()

Anupama Mishra
Thread synchronization
Synchronized methods

• If one thread tries to read the data and other thread tries to update
the same data, it leads to inconsistent state.
• This can be prevented by synchronising access to the data.
• Use “Synchronized” methods:

public synchronized void update()


{

}

Anupama Mishra

You might also like