Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

MultithreadingLecture

The document outlines the learning objectives and content for a course on Object Oriented Programming using Java, focusing on multitasking and multithreading concepts. It explains the differences between process-based and thread-based multitasking, the life cycle of threads, and methods for creating and managing threads in Java. Additionally, it discusses thread priorities and the role of the thread scheduler in managing execution order.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

MultithreadingLecture

The document outlines the learning objectives and content for a course on Object Oriented Programming using Java, focusing on multitasking and multithreading concepts. It explains the differences between process-based and thread-based multitasking, the life cycle of threads, and methods for creating and managing threads in Java. Additionally, it discusses thread priorities and the role of the thread scheduler in managing execution order.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

AMITY INSTITUTE OF INFORMATION

TECHNOLOGY

BCA B,C & D


Semester-III
Object Oriented Programming Using
Java
Prof(Dr)Laxmi Ahuja
Learning Objectives
•Imparting java programming skill to students

•Knowledge of object oriented paradigm in


context of Java programming language

•Designing desktop applications using latest


Java based API
Contents to be Covered
• Introduction to Multi Tasking
• Types of Multitasking
• Process Based and Thread Based
• Multitasking and Multithreading
• Life Cycle of Multithreading
• Types of Thread Implementation
Introduction
Multitasking :Executing Several task simultaneously or Doing several task simultaneously

Multitasking is of two types

• Process Based: Process is a Program with multiple threads i.e th1,th2,th3


• Thread Based:Thread is Individual part or unit of a running program(Thread 1)

Process based :Executing several task simultaneously where each task is a separate Independent
Process and is not dependent on each other for example : Typing a java program in Editor while
typing ,students listens audio song from the same system and at the same time download some file from
Internet .Every activity is an Independent process such an activity is called Process based ,where each
task is a separate Independent process and all are executing simultaneously and all are Independent
process (no dependency)this is the concept of Process based (Process based is considered at OS
level whereas at Programmer level we consider Thread based (Each task is a separate Independent
application, Multiple Independent Programs will be there)
Thread Based:

Thread is a individual unit of a Program or a individual part of a


running program
Executing multiple tasks separately where one program is divided into
multiple Independent tasks ie. Executing several Independent parts
simultaneously and where each task is a separate independent part of
same program and each Independent part is called a thread(One Prog
multiple Independent parts)

• Process is multiple threads of a Program


• Prog will be having multiple threads
• Individual part is a thread
MULTITASKING AND MULTITHREADING
MULTITHREADING
MULTITASKING
• In Multithteading program(or
• It is the process of executing several
process) is divided into two or
tasks at the same time.
more subprograms,which can be
• Execution of Running Program implemented at the same time
• Each program has its own address in parallel.
space(Every program will be having its • Individual part of a program
own address space)
• Multiple threads may share
common address space
• Heavy Weight Process(it require more • Light Weight Process
resources)
MULTITASKING AND
MULTITHREADING
MULTITASKING MULTITHREADING
• Context switching is high
cost(Switching from one process
to another process if one process • Context switching is low as each
comes from high priority the thread share common address
other process will be in block space
state or waiting state • Inter thread communication is
• Inter Process communication is inexpensive(Here multiple
expensive(Here each and every threads share common address
prog share its own address space space so communication
so that’s why its is expensive between them is inexpensive
MULTITASKING AND
MULTITHREADING
MULTITASKING MULTITHREADING
• It is the process of executing several • Here a program is divided into two or
task simultaneously more subprograms(process,which
• It is divided into two can be implemented at the same
Process based Multitasking (Facebook time in parallel i.e In text Editor we
chat and listening music)(two process are editing and printing (dividing a
running simultaneously and single program into sub parts or
threads or class A having two
Thread Based Multitasking(In text programs m1 and m2 and both run
Editor we have Text Editing and together as m1 is separate thread
printing text one process having two and m2 are considered as threads
threads or sub parts)
• It is under the control of Java
• Multitasking is not under control of
Java
BENEFITS of Multithreading
• Enable programmers to do multiple things at one time(if process divide into multiple
threads then processor can do two different tasks at one time example(one prog
having two tasks update information and print information both run concurrently
• Programmers can divide a long program into threads and execute them in parallel
which will eventually increase speed of program execution(If different methods are
there from 1 to 10methods(if not threads they run one after the other but if we make
all the ten methods as threads then they can run concurently and time will be
improved)
• Improved Performance and Concurrency
• Simultaneous access to multiple applications(Simultaneous access to multiple
Thread Life Cycle
THREAD LIFE CYCLE
Whenever thread is created that will be in a new state
In java Thread is a class

As we know that class consist of methods variables and constructors so here Thread class consist of a number of
Methods and to access methods of Threads we have to create object of a class that we called as Thread

After creation of that thread then it will be in NEW Born state


After New born state
We have RUNNABLE state i.e. Ready to RUN(or waiting for process) i.e. if the thread is ready to execute its
task then it will be in RUNNABLE state

RUNNING—if processor is available then it move to the running state if the thread is allocated to the processor
then it starts execution

If any I/O interruption occur, then thread move to the waiting or BLOCKED STATE
After Completion of I/O Event again it will move to the RUNNING STATE or It may move to the RUNNABLE state
If processor available, it moves to the running state or if the processor is busy it moves to the runnable state
If no interruption occurs and after execution of the process it will move to the stop state ie termination
FIVE STATES of THREAD
• NEW
• RUNNABLE
• RUNNING
• WAITING/BLOCKED
• STOP

Thread class have number of Methods so by accessing those methods this thread will change its
state

//Creation of Object for a class


Thread t=new Thread()
t.start();//when this method starts it implicitly calling run()
//Move to the Runnable state
t.run();
t.sleep/t.wait//move to the waiting or blocked state
After Intervals //Here we pass some parameters that how many intervals threads will be in waiting state
t.stop() After completion of task
There are Five stages of life cycle of
thread
• New
• Runnable
• Running
• Waiting
• Dead
Life Cycle of Thread
A thread can be in one of the following states:

NEW – A thread that has not yet started is in this state.

RUNNABLE – A thread executing in the Java virtual machine is in this state.

RUNNING

BLOCKED – A thread that is blocked waiting for a monitor lock is in this state.

WAITING – A thread that is waiting indefinitely for another thread to perform a


particular action is in this state.

TERMINATED – A thread that has exited is in this state.


• In Java.lang we have both class and Interface .

• Java supports java.lang package in the thread class.

• We need to extend the same or by implementing the


interface Runnable in class whose instances are to be
executed by a thread should implement the runnable
interface.

• The class must define a method called run which needs to


overwrite to start the thread
How to start Thread
class threaddemo
{
public static void main(String args[])
{
//when main method starts how many threads will be there
{
//only one flow of execution i.e. main thread
Mythread t=new mythread();//main thread creating child thread
object//known as instantiation of Object

//child thread created but not started


t.start();//Here main thread starts child thread
//we have only one thread i.e. main()
//now two thread are there
Main and child
Thread Creation in Java
Main Thread: Every Time a Java Program starts up, one thread
begins running which is called as the main thread of the program
because it is the one that is executed when your program
begins.

Two ways of defining Thread:

Firstly, by Extending Thread class


Secondly ,By Implementing Runnable Interface
Two ways of defining Thread-Thread is a flow
of execution
Firstly, by Extending Thread class
Secondly ,By Implementing Runnable Interface
Second approach is best

//How to define a Thread //thread can be define by extending thread class

class thread1 extends Thread


{
public void run() //Override the run() method //run() already available in Thread class ,override it
{
for(int i=0;i<10;i++) //code written in run() is a job of thread
{
System.out.println("child Thread");
}
}
} /This part will be executed by child thread
class Thread2
{
public static void main(String args[])main thread is only one thread // main thread create child thread object
{
thread1 t=new thread1();//main thread creating child thread object and known as instantiatiaion of thread

t.start();//starting of a thread
for(int i=0;i<10;i++);
{
System.out.println("Main Thread");}
}
//This part will be executed by Main Thread

//Save both the program in one file and save it with thread2 .java
Javac thread2.java
Java thread2

//Every java program contains one main thread


class thread1 extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("child Thread");
}
}
}
class thread2
{
public static void main(String args[])
{
thread1 t=new thread1();
t.start();
for(int i=0;i<10;i++)
{
System.out.println("Main Thread");
}
}
}
OUTPUT

In multithreading we cannot expect the output that whether main thread will execute first or
child thread but all the threads run simultaneously
TWO WAYS

Extending Thread Class Implementing runnable Interface


class t1 extends Thread class t1 implements Runnable
{ {
public void run() public void run()
{ {
System.out.println("Thread t2"); System.out.println("Thread t2");
} }
public static void main(String args[]) public static void main(String args[])
{ {
t1 ob=new t1(); t1 ob=new t1();
t1.start(); Thread t=new Thread(ob);//we have to use Thread Class
}} t1.start();}}
class t1 implements Runnable
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("Thread1:" +i);
}}}
class t2 implements Runnable
{
public void run()
{
for(int j=0;j<5;j++)
{
System.out.println("Thread t2" +j);
}}
public static void main(String args[])
{
t1 ob=new t1();
t2 ob1=new t2();
Thread th=new Thread(ob);//thread class object
Thread th1=new Thread(ob1);
th.start();//Now call the start()
th1.start();
}}
Thread Scheduler
• Responsible to schedule of Threads
• It’s a part of JVM
• If multiple threads are there but processor is one and in which order
these thread will be executed is taken care by scheduler

• Scheduler is responsible the order of thread

• Which Algorithm will be used by scheduler is decided by JVM


• Multithreading is used when we have Independent jobs.
BY Implementing Runnable Interface
• Runnable Interface is available in java.lang
• It contains only one method ie run() under runnable interface

// This prog is defining job of Thread


class thread1 implements Runnable //Write a class that implements Runnable interface directly
{
public void run() //Implement run() as it contains only one method
{
for(int i=0;i<10;i++)
{
System.out.println("child Thread");
}
}
}
class thread2
{
public static void main(String args[]) // only one thread i.e. main() thread
{
thread1 r=new thread1(); //main() or thread creates runnable object but runnable
does not //contain start() only one method i.e. run()
// For start we create object of Thread class
Thread t=new Thread(r);//Here create Thread class object and //under that use
start()
t.start();
for(int i=0;i<10;i++)
{
System.out.println("Main Thread");
}
}
}
class thread1 implements Runnable
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("child Thread");
}
}
}
class thread2
{
public static void main(String args[])
{
thread1 r=new thread1();
Thread t=new Thread(r);//Here create Thread class object and //under that use start()
t.start();
for(int i=0;i<10;i++)
{
System.out.println("Main Thread");
}
}
By using Runnable Interface –use three
threads simultaneously
class thread1 implements Runnable
{
public void run()
{
for(int i=0;i<5;i++) // job of thread
{
System.out.println("Thread1:" +i);
}
}}
class thread2 implements Runnable
{
public void run()
{
for(int j=0;j<5;j++) // job of thread
{
System.out.println("Thread2:" +j);
}}}
class thread3 implements Runnable
{
public void run()
{
for(int k=0;k<5;k++) // job of thread
{
System.out.println("Thread3:" +k);
}}
public static void main(String args[])
{
thread1 th1=new thread1();
thread2 th2=new thread2();
thread3 th3=new thread3();
Thread t1=new Thread(th1);
Thread t2=new Thread(th2);
Thread t3=new Thread(th3);
t1.start();
t2.start();
t3.start();
Thread Priorities
• Every thread in java has some priority
• It may be default priority generated by JVM
• Or
• It may be customized priority provided explicitly by programmer

• Valid range of Thread Priority


• 0-10 or 1-10
• It is not Index the priority is always 1 to 10 but not 0-10
• MINIMUM is 1
• MAXIMUM is 10
• To represent these priorities ,Thread class contain constants i.e.
• Thread.MIN_PRIORITY==1
• Thread.NORM_PRIORITY==5
• Thread.MAX_PRIORITY==10
• Every thread in java has some priority It may be default priority generated by JVM or customized
priority provided by programmer
THANK YOU

You might also like