Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

MULTITHREADED PROGRAMMING

THREAD: INTRODUCTION

⦿A Thread may be defined as a separate sequential flow of


control within the main program.
⦿ Threads are used in a program for achieving specific tasks.

⦿ Multithreading means, using different threads to perform


different parts of a task.
⦿ In Multithreading, a task is divided into different subtasks
and different threads, which run simultaneously, for
executing these subtasks.
MULTITASKING VS MULTITHREADING
Multitasking
⦿ Multitasking is a process of executing multiple tasks simultaneously.
⦿ Multitasking can be achieved by two ways:
1. Process-based Multitasking(Multiprocessing)
2. Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
⦿ Each process have its own address in memory i.e. each process
allocates separate memory area.
⦿ Process is heavyweight.
2) Thread-based Multitasking (Multithreading)
⦿ Threads share the same address space.
⦿ Thread is lightweight.
MULTITHREADING
⦿ Multiprocessing and multithreading, both are used to
achieve multitasking.
⦿ But we use multithreading than multiprocessing because
threads share a common memory area.
⦿ They don't allocate separate memory area so saves
memory
⦿ Java Multithreading is mostly used in games, animation
etc.
⦿ When multiple threads are created, they can be executed in
any order.
MULTITHREADING

• As shown in the figure,


thread is executed inside
the process.
• There can be multiple
processes inside the OS
and one process can
have multiple threads.
THREAD CLASS
⦿ Java provides Thread class to achieve thread
programming.
⦿ Thread class provides constructors and
methods to create and perform operations on a
thread.
⦿ Thread class extends Object class and
implements Runnable interface.
THREAD CLASS METHODS
Method Description
start() It is used to start the execution of the
thread.

run() It is used to do an action for a thread.

sleep() It sleeps a thread for the specified


amount of time.

It returns a reference to the currently


executing thread object.
currentThread()

setPriority() It changes the priority of the thread.

getPriority() It returns the priority of the thread.

isAlive() It tests if the thread is alive.

getId() It returns the id of the thread.


Method Description
suspend() It is used to suspend the thread.

resume() It is used to resume the suspended


thread.
stop() It is used to stop the thread.
destroy() It is used to destroy the thread group
and all of its subgroups.
interrupt() It interrupts the thread.
notify() It is used to give the notification for
only one thread which is waiting for a
particular object.
notifyAll() It is used to give the notification to all
waiting threads of a particular object.
getState() It returns the state of the thread.
It returns the name of the thread.
getName()
CREATING A THRED
⦿ Java defines two ways by which a thread can be created.
1. By implementing the Runnable interface.
2. By extending the Thread class.
1. By Implementing the Runnable Interface
⦿ The easiest way to create a thread is to create a class that implements the
runnable interface.
⦿ After implementing runnable interface , the class needs to implement the
run() method.ublic void run()
⦿ run() method introduces a concurrent thread into your program. This thread
will end when run() returns.
⦿ You must specify the code for your thread inside run() method.
CREATING A THREAD BY IMPLEMENTING runnable
Example:1
class A implements Runnable
{ public void run()
{System.out.println(“thread started running..");}
}
Class Demo{
public static void main( String args[] ) {
A obj = new A();
Thread t = new Thread(obj); //passing class instance in
Thread object’s constructor
t.start();
}
}
Output : thread started running..
⦿ To call the run() method, start() method is used.

⦿ On calling start(), a new stack is provided to the thread.


⦿ NOTE:
When the class implements the runnable interface, the thread can be run
by passing an instance of the class to a Thread object's constructor and
then calling the thread's start() method
Example:2
public class B implements Runnable {
public static void main(String[] args) {
B b1= new B();
Thread t = new Thread(b1);
t.start();
}
public void run() {
System.out.println("This code is running in a thread");
}
}

o/p: This code is running in a thread


CREATING A THREAD BY EXTENDING THREAD CLASS
2. By extending Thread class
⦿ This is another way to create a thread by a new class that extends
Thread class.
class
class AAextends
extendsThread
Thread
{ public void run(){
public void run(){
System.out.println(“thread started running..");}
System.out.println(“thread started running..");}
}
}
Class MyThreadDemo{
publicMyThreadDemo{
Class static void main( String args[] ) {
A obj = new A();
public static void main( String args[] ) {
obj.start();
} A obj = new A();
}
obj.start();
}}

Output : concurrent thread started running..


⦿ NOTE:
When any class extends the Thread class, the
thread can be run by creating an instance of
the class and call its start() method:
Example:2
public class B extends Thread {
public static void main(String[] args) {
B b1= new B();
b1.start();
}
public void run() {
System.out.println("This code is running in a thread");
}
}

o/p: This code is running in a thread


THREAD CLASS VS RUNNABLE INTERFACE
⦿ If we extend the Thread class, our class cannot extend any
other class because Java doesn’t support multiple inheritance.
But, if we implement the Runnable interface, our class can still
extend other base classes.
⦿ We can achieve basic functionality of a thread by extending
Thread class because it provides some inbuilt methods like
yield(), interrupt() etc. that are not available in Runnable
interface.
LIFE CYCLE OF A THREAD

⦿ During the life time of a Thread, there are many


states it can enter,
They include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
LIFE CYCLE OF A THREAD
LIFE CYCLE OF A THREAD
1. Newborn State:
⦿ When we create a thread object, the thread is born and is said to be in
newborn state.
⦿ The thread is not yet scheduled for running.
⦿ At this state, we can do only one of the following things with it:
* Schedule it for running using start( ) method.
* Kill it using stop () method.

2. Runnable State:
⦿ The Runnable state means that the thread is ready for execution and is
waiting for the availability of the processor.
⦿ That is, the thread has joined the queue of threads that are waiting for
execution.
LIFE CYCLE OF A THREAD
3. Running State:
⦿ Running means that the processor has given its time to the
thread for its execution.
⦿ The thread runs until it relinquishes (give up) control on its own.
⦿ It has been suspended using suspend( ) method.
⦿ A suspended thread can be revived by using the resume( )
method.
⦿ we can put a thread to sleep for a specified time period using the
method sleep (time) where time is in milliseconds.
⦿ This means that the thread is out of the queue during this time
period.
⦿ It has been told to wait until some events occur.
⦿ This is done using the wait ( ) method.
⦿ The thread can be scheduled to run again using the notify ( )
method.
LIFE CYCLE OF A THREAD
4. Blocked State:
⦿ A thread is set to be blocked when it is prevented from entering into
the Runnable state and subsequently the running state.
⦿ This happens when the thread is suspended, or sleeping, or waiting in
order to satisfy certain requirements.

5. Dead State:
⦿ Every thread has a life cycle.

⦿ A running thread ends its life when it has completed executing its run
( ) method.
⦿ It is a natural death.

⦿ However, we can kill it by sending the stop message to it at any state


thus causing a premature death to it.
⦿ A thread can be killed as soon it is born, or while it is running, or
even when it is in “not Runnable” (blocked) condition.
BLOCKING THREADS
⦿ Blocking thread is nothing but suspending the execution of
thread temporarily.
⦿ Threads can be blocked using different methods such as:
◼ Sleep():blocks thread for specified time
◼ Suspend():blocks thread until next order
◼ Wait():bloks thread until certain condition occurs.
EXAMPLE
public class JavaSuspendExp extends Thread
{
public void run()
{
for(int i=1; i<5; i++)
{
try
{
sleep(500); //makes thread to sleep fro 500 mili seconds
System.out.println(Thread.currentThread().getName());
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{

JavaSuspendExp t1=new JavaSuspendExp (); //creating thread 1


JavaSuspendExp t2=new JavaSuspendExp (); //creating thread 2
t1.start(); //invokes run() for thread1
t2.start(); // invokes run() for thread2
t2.suspend(); //suspends thread2 temporarily
System.out.println(“t2 suspended”);
t2.resume(); //resumes thread2 from suspension
t3=2.stop(); //stops thread3 forcefully and moves thread3 to dead state
System.out.println(“t2 stopped”);

}
}
THREAD METHODS
⦿ Thread class methods will be used to control the behavior of
a thread.
⦿ In the given examples 1 and 2 yield() is used.
⦿ A yield() method is a static method of Thread class and it
can stop the currently executing thread and will give a
chance to other waiting threads to run. i.e., By using
yield() if currently running thread is not doing anything
particularly important and if any other threads or processes
need to be run, they should run. Otherwise, the current
thread will continue to run.
EXAMPLE 1
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; ++i) {
Thread.yield(); // By calling this method, MyThread stop its execution and giving a chance to a main thread
System.out.println("Thread started:" + Thread.currentThread().getName());
}
System.out.println("Thread ended:" + Thread.currentThread().getName());
}
}
public class YieldMethodTest {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
for (int i = 0; i < 5; ++i) {
System.out.println("Thread started:" + Thread.currentThread().getName());
}
System.out.println("Thread ended:" + Thread.currentThread().getName());
}
}
EXAMPLE 2
class A extends Thread{
public void run() {
for(int i=1;i<=5;i++) {
if(i==1)
yield();
System.out.println("from thread A:i="+i); }
System.out.println("Exiting from A");
}
}
class B extends Thread{
public void run() {
for(int j=1;j<=5;j++) {
System.out.println("from thread B:j="+j);
if(j==3)
stop();
}
System.out.println("Exiting from B");
}
}
public class ThreadEx{
public static void main(String args[]) {
A a1=new A(); //creating threads
B b1=new B();
System.out.println("Start thread A");
a1.start();
System.out.println("Start thread B");
b1.start();
}
}
THREAD EXCEPTIONS
class MyThread extends Thread{
public void run()
{
System.out.println("Throwing in " +"MyThread");
throw new RuntimeException();
}
}
public class Main {
public static void main(String[] args)
{
MyThread t = new MyThread();
t.start();
try {
Thread.sleep(1000);
} catch (Exception x) { System.out.println("Caught it" + x);
}
System.out.println("Exiting main");
}
}
THREAD PRIORITY
⦿ In java,each thread is assigned with a priority which affects the order of their
execution.

⦿ Threads with same priority will be treated equally by java scheduler and they share
processor on FIFO basis.

⦿ In java setPriority() method will be used to set the priority of a thread.

Syntax: ThreadName.setPriority(intNumber);

intNumber: an integer value to specify thread priority.


⦿ Priority value can be set between 1 to 10.

1-min.priority

5-normal priority

10-max.priority

⦿ The Thread class defines several priority constants.Those are:

MIN_PRIORITY=1

NORM_PRIORITY=5

MAX_PRIORITY=10
EXAMPLE:1
class TestPriority extends Thread{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestPriority m1=new TestPriority();
TestPriority m2=new TestPriority();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
EXAMPLE 2
public class PriorEx extends Thread{
public void run() {
System.out.println("Thread is Running..");
}
public static void main(String args[]) {
PriorEx p1=new PriorEx();
PriorEx p2=new PriorEx();
PriorEx p3=new PriorEx();
p1.start();
p2.start();
p1.setPriority(2);
p2.setPriority(6);
p3.setPriority(9);
System.out.println("p1 thread priority"+p1.getPriority());
System.out.println("p2 thread priority"+p2.getPriority());
System.out.println("p3 thread priority"+p3.getPriority());
System.out.println("AFTER CHANGING PRIORITY");
System.out.println("p1 thread priority"+"\t"+p1.MAX_PRIORITY);
System.out.println("p2 thread priority"+"\t"+p2.MIN_PRIORITY);
System.out.println("p3 thread priority"+"\t"+p3.NORM_PRIORITY);
}
}

OUTPUT:
Thread is Running..
Thread is Running..
p1 thread priority 2
p2 thread priority 6
p3 thread priority 9
AFTER CHANGING PRIORITY
p1 thread priority 10
p2 thread priority 1
p3 thread priority 5
SYNCHRONIZATION
⦿ When multiple threads are competing for same resources then they may lead to
serious problems.For Example,if thread t1 is trying to read a record from file
while another thread t2 is writing the same file then thread t1 may read wrong
data.This problem can be eliminated by using synchronization technique in
java.

⦿ Synchronization in java is the capability to control the access of multiple


threads to any shared resource.

⦿ By using synchronization, problem discussed in above example can be


solved.i.e.when thread t1 acquires a file (shared resource)for read operation
then that file will be locked so that no other threads can access the same file for
some other operation at same time until lock is released by thread t1.
EXAMPLE:WITHOUT SYNCHRONIZATION
class Table{ class MyThread2 extends Thread{
void printTable(int n){ //method not synchronized Table t;
MyThread2(Table t){
for(int i=1;i<=5;i++){ this.t=t;
System.out.println(n*i); }
public void run()
try{
{
Thread.sleep(400); t.printTable(100);
}catch(Exception e) }
}
{
System.out.println(e); class TestSynchronization1
{
}
public static void main(String args[])
} {
} Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
} MyThread2 t2=new MyThread2(obj);
class MyThread1 extends Thread{ t1.start();
t2.start();
Table t; }
MyThread1(Table t){ }
this.t=t;
}
public void run(){
t.printTable(5);
}
}
EXAMPLE:WITH SYNCHRONIZATION
class Table{
synchronized void printTable(int n){ class MyThread2 extends Thread{
Table t;
for(int i=1;i<=5;i++){
MyThread2(Table t){
System.out.println(n*i); this.t=t;
try{ }
Thread.sleep(400); public void run(){
}catch(Exception e) t.printTable(100);
}
{ }
System.out.println(e);
} class TestSynchronization1
} {
public static void main(String args[])
}
{
} Table obj = new Table();
class MyThread1 extends Thread{ MyThread1 t1=new MyThread1(obj);
Table t; MyThread2 t2=new MyThread2(obj);
MyThread1(Table t){ t1.start();
t2.start();
this.t=t;
}
} }
public void run(){
t.printTable(5);
}
}

You might also like