SlideShare a Scribd company logo
Multi Tasking
Executing several tasks simultaneously is the concept
of multi tasking
There are two types of multi tasking
1.Process based
2. Thread based multi tasking
Process based multi tasking
Executing several tasks simultaneously where each
task is separate independent program(process) is
called process based multi tasking.
Example
While writing java program we can listen songs using
the same system, at the same time we can
download a file from the net.
All these tasks will be executed simultaneously and
independent of each other. Hence it is called
process based multi tasking.
Process based multi tasking is best suitable at OS level
Thread based multi tasking
Executing several tasks simultaneously where each
task is a separate independent part of the same
program is called Thread based multi tasking and
each independent part is called thread.
Thread based multitasking is best suitable at
programmatic level.
Differences between Process-based Multitasking & Thread-based Multitasking
Process-based Multitasking
1. Each process have its own address in memory i.e. each process
allocates separate memory area.
2. Process is heavyweight.
3. Cost of communication between the process is high.
4. Switching from one process to another require some time for
saving and loading registers, memory maps, updating lists etc.
Thread-based Multitasking
1. Threads share the same address space.
2. Thread is lightweight.
3. Cost of communication between the thread is low.
The main important application areas of
multithreading are
1.To develop multimedia graphics
2.To develop animations
3.To develop video games
4.To develop web servers and application servers etc.
When compared with old languages developing
multithreaded application is very easy. java
provides inbuilt support with rich API.
(Thread,Runnable,threadGropup)
Life cycle of a Thread
What is Thread
A thread is a lightweight sub process, a smallest unit
of processing. It is a separate path of execution.
A thread can be in one of the five states.
1.New/Born
2.Runnable/Ready
3.Running
4.Blocked
5.Terminated/Dead
multhi threading concept in oops through java
1. New : A thread begins its life cycle in the new
state. It remains in this state until the start()
method is called on it.
2. Runnable : After invocation of start() method on
new thread, the thread becomes runnable.
3. Running : A thread is in running state if the thread
scheduler has selected it.
4. Waiting : A thread is in waiting state if it waits for
another thread to perform a task. In this stage the
thread is still alive.
5. Terminated : A thread enter the terminated state
when it complete its task.
Creating a Thread
There are two ways to create a thread:
1.By extending Thread class
2.By implementing Runnable interface.
By extending Thread class
Class Mythread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(“run method”);
}
}
}
Class Test
{
public static void main(String args[])
{
Mythread t=new Mythread();
t.start();
for(int i=0;i<10;i++)
{
System.out.println(“main method”);
}
}
}
Case 1:
If we call run() method directly without using
start() method
public static void main( String args[] )
{
MyThread t = new MyThread();
t.run();
}
Difference between t.start() and t.run()
In the case of t.start() a new thread will be created
which responsible for the execution of run method.
But in the case of t.run() a new thread won’t be
created and run method will be executed just like a
normal method call by main thread.
Hence Multithreading won't be there.
Case 2:
A thread cannot be started twice. If you try to do so,
IllegalThreadStateException will be thrown.
Class Test
{
public static void main(String args[])
{
Mythread t=new Mythread();
t.start();
t.start();//Exception thrown
}
}
By implementing Runnable interface
Class MyRunnable implements Runnable
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(“child thread”);
}
}
}
Class ThreadDemo
{
public static void main(String args[])
{
MyRunnable r=new MyRunnable();
Thread t=new Thread(r);
t.start();
for(int i=0;i<10;i++)
{
System.out.println(“main thread”);
}
}
}
MyRunnable r=new MyRunnable();
Thread t=new Thread();
Thread t1=new Thread(r);
Case1: t.start(); ->it execute thread run method.
Case 2:t.run();-> it executes thread run method.
Case3:t1.start();->it execute runnable run method
Case4:t1.run();->it executes runnable run method
without creating thread.
Case 5:r.start();->compile time error.
Case6: r.run();-> it executes runnable run method
without creating thread.
Getting and setting name of thread
Every thread in java has some name. it may be default
name generated by JVM or Customized name
provided by programmer.
We can get and set the name of a thread by using the
following two methods of thread class.
1.Public final String getName()
2.Public final void setName(String name)
Example
Class MyThread extends Thread
{
}
Class Test
{
public static void main(String args[])
{
System.out.println(Thread.currentThread().getName());
MyThraed t=new MyThread();
System.out.println(t.getName());
Thread.currentThread().setName(“CMR”);
System.out.println(Thread.currentThread().getName());
}
}
Creating Multiple Threads
class NewThread implements Runnable
{
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
//System.out.println("New thread: " + t);
t.start(); // Start the thread
}
public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo
{
public static void main(String args[])
{
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Thread Priorities
Every thread in java has some priority it may be
default priority generated by JVM or customized
priority provided by programmer
The valid range of thread priorities is 1 to 10.
where
1—MIN_PRIORITY
10---MAX_PRIORITY
Thread class defines the following constants to
represent some standard priorities
Thread.MIN_PRIORITY------1
Thread.NORM_PRIORITY-----5
Thraed.MAX_PRIORITY---------10
Thread scheduler will use priorities while allocating
processor.
The Thread which is having highest priority will get
chance first.
If two threads having same priority then we can’t
except exact execution order. it depends on thread
scheduler.
Thread class defines the following methods to get and
set priority of a thread.
public final int getPriority().
Public final void setPriority(int p)
Default Priority
The default priority only for the main thread is 5.
But for all remaining threads default priority will be
inherited form parent to child. i.e what ever priority
parent thread has the same priority will be there for
the child thread.
Example:
Class Mythread extends Thread
{
}
Class thredDemo
{
Public static void main(String args[])
{
System.out.println(Thread.currentThread().getPriority());
//Thread.currentThread().setPriority(8);
Mythread t=new Mythread();
System.out.println(t.getPriority());
}
}
Setting the thread Priority
class Mythread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Child thread");
}
}
}
class ThredPriorityDemo1
{
public static void main(String args[])
{
Mythread t=new Mythread();
t.setPriority(10);
t.start();
for(int i=0;i<10;i++)
{
System.out.println("Main thread");
}
}
}
Output
Child thread –10 times
Main thread—10 times
note
Some platforms won’t provide support for thread priorities.
important methods of thread class
To prevent a thread execution the following methods
are used.
1.yield()
2.join()
3.sleep()
Yield()
Yield method pauses the currently executing
thread temporarily for giving a chance to the
remaining waiting threads of the same priority
to execute. If there is no waiting thread or all
the waiting threads have a lower priority then
the same thread will continue its execution.
Syntax
Public static native void yield()
Example
Class mythread extends Thread
{
Public void run()
{
For(int i=0;i<10;i++)
{
System.out.println(“child thread”);
Thread.yield();
}
}
}
Class ThreadYieldDemo
{
Public sataic void main(String args[])
{
Mythread t=new Mythread();
t.strat();
for(int i=0;i<10;i++)
{
System.out.println(“main thread”);
}
}
}
Join ()
If a thread wants to wait until completing some other thread
then we should go for join() method.
example
If a thread T1 wants to wait until completing T2 then T1 has to
call T2.join().If T1 executes T2.join() then immediately T1 will
be entered into waiting state until T2 completes. Once T2
completes then T1 can continue its execution.
Syntax
Public final void join() throws InterruptedException
Public final void join(long ms) throws InterruptedException
Public final void join(long ms, int ns) throws
InterruptedException
Example
class Mythread extends Thread
{
public void ru()
{
for(int i=0;i<10;i++)
{
System.out.println("seetha Thread");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
}
}
}
}
class ThreadJoinDemo
{
public static void main(String args[])throws InterruptedException
{
Mythread t=new Mythread();
t.start();
t.join();
for(int i=0;i<10;i++)
{
System.out.println("rama Thread");
}
}
}
Sleep ()
If a thread don’t want to perform any operation per a
particular amount of time then we should go for
sleep() method.
Syntax
Public static native void sleep(long ms) throws
InterruptedException
Public static void sleep(long ms, int ns) throws
InterruptedException
Example
class SlideRotator
{
public static void main(String args[])throws
InterruptedException
{
for(int i=0;i<10;i++)
{
System.out.println("Slide:"+i);
Thread.sleep(5000);
}
}
}

More Related Content

PPTX
Internet Programming with Java
PPT
Chap2 2 1
DOCX
Threadnotes
PPTX
multithreading,thread and processinjava-210302183809.pptx
PPTX
U4 JAVA.pptx
PDF
Java threads
PPTX
multithreading to be used in java with good programs.pptx
Internet Programming with Java
Chap2 2 1
Threadnotes
multithreading,thread and processinjava-210302183809.pptx
U4 JAVA.pptx
Java threads
multithreading to be used in java with good programs.pptx

Similar to multhi threading concept in oops through java (20)

PPTX
OOPS object oriented programming UNIT-4.pptx
PPTX
Multithreading in java
PPTX
Concept of Java Multithreading-Partially.pptx
PPT
PPTX
Threads in Java
PPT
Java Multithreading
PPT
Java multithreading
PPT
web programming-Multithreading concept in Java.ppt
PPTX
Multithreading in java
PPT
Multithreading
 
PDF
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
PPT
multithreading
PPT
PDF
Multithreading Introduction and Lifecyle of thread
PDF
Unit-3 MULTITHREADING-2.pdf
PPTX
Multi-Threading in Java power point presenetation
PDF
Class notes(week 9) on multithreading
PPTX
Multithreading in java
PPTX
Multithreading in java
PPT
Md09 multithreading
OOPS object oriented programming UNIT-4.pptx
Multithreading in java
Concept of Java Multithreading-Partially.pptx
Threads in Java
Java Multithreading
Java multithreading
web programming-Multithreading concept in Java.ppt
Multithreading in java
Multithreading
 
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
multithreading
Multithreading Introduction and Lifecyle of thread
Unit-3 MULTITHREADING-2.pdf
Multi-Threading in Java power point presenetation
Class notes(week 9) on multithreading
Multithreading in java
Multithreading in java
Md09 multithreading
Ad

More from Parameshwar Maddela (11)

PPTX
EventHandling in object oriented programming
PPTX
Exception‐Handling in object oriented programming
PPTX
working with interfaces in java programming
PPTX
introduction to object orinted programming through java
PDF
Object oriented programming -QuestionBank
PPT
file handling in object oriented programming through java
PPTX
22H51A6755.pptx
PPTX
swings.pptx
PDF
03_Objects and Classes in java.pdf
PDF
02_Data Types in java.pdf
PPT
Intro tooop
EventHandling in object oriented programming
Exception‐Handling in object oriented programming
working with interfaces in java programming
introduction to object orinted programming through java
Object oriented programming -QuestionBank
file handling in object oriented programming through java
22H51A6755.pptx
swings.pptx
03_Objects and Classes in java.pdf
02_Data Types in java.pdf
Intro tooop
Ad

Recently uploaded (20)

PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Lesson notes of climatology university.
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Insiders guide to clinical Medicine.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
RMMM.pdf make it easy to upload and study
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Cell Structure & Organelles in detailed.
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Renaissance Architecture: A Journey from Faith to Humanism
GDM (1) (1).pptx small presentation for students
Lesson notes of climatology university.
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Insiders guide to clinical Medicine.pdf
Supply Chain Operations Speaking Notes -ICLT Program
human mycosis Human fungal infections are called human mycosis..pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
RMMM.pdf make it easy to upload and study
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Microbial disease of the cardiovascular and lymphatic systems
Final Presentation General Medicine 03-08-2024.pptx
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf

multhi threading concept in oops through java

  • 1. Multi Tasking Executing several tasks simultaneously is the concept of multi tasking There are two types of multi tasking 1.Process based 2. Thread based multi tasking
  • 2. Process based multi tasking Executing several tasks simultaneously where each task is separate independent program(process) is called process based multi tasking. Example While writing java program we can listen songs using the same system, at the same time we can download a file from the net. All these tasks will be executed simultaneously and independent of each other. Hence it is called process based multi tasking. Process based multi tasking is best suitable at OS level
  • 3. Thread based multi tasking Executing several tasks simultaneously where each task is a separate independent part of the same program is called Thread based multi tasking and each independent part is called thread. Thread based multitasking is best suitable at programmatic level.
  • 4. Differences between Process-based Multitasking & Thread-based Multitasking Process-based Multitasking 1. Each process have its own address in memory i.e. each process allocates separate memory area. 2. Process is heavyweight. 3. Cost of communication between the process is high. 4. Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc. Thread-based Multitasking 1. Threads share the same address space. 2. Thread is lightweight. 3. Cost of communication between the thread is low.
  • 5. The main important application areas of multithreading are 1.To develop multimedia graphics 2.To develop animations 3.To develop video games 4.To develop web servers and application servers etc. When compared with old languages developing multithreaded application is very easy. java provides inbuilt support with rich API. (Thread,Runnable,threadGropup)
  • 6. Life cycle of a Thread What is Thread A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution. A thread can be in one of the five states. 1.New/Born 2.Runnable/Ready 3.Running 4.Blocked 5.Terminated/Dead
  • 8. 1. New : A thread begins its life cycle in the new state. It remains in this state until the start() method is called on it. 2. Runnable : After invocation of start() method on new thread, the thread becomes runnable. 3. Running : A thread is in running state if the thread scheduler has selected it. 4. Waiting : A thread is in waiting state if it waits for another thread to perform a task. In this stage the thread is still alive. 5. Terminated : A thread enter the terminated state when it complete its task.
  • 9. Creating a Thread There are two ways to create a thread: 1.By extending Thread class 2.By implementing Runnable interface.
  • 10. By extending Thread class Class Mythread extends Thread { public void run() { for(int i=0;i<10;i++) { System.out.println(“run method”); } } } Class Test { public static void main(String args[]) { Mythread t=new Mythread(); t.start(); for(int i=0;i<10;i++) { System.out.println(“main method”); } } }
  • 11. Case 1: If we call run() method directly without using start() method public static void main( String args[] ) { MyThread t = new MyThread(); t.run(); }
  • 12. Difference between t.start() and t.run() In the case of t.start() a new thread will be created which responsible for the execution of run method. But in the case of t.run() a new thread won’t be created and run method will be executed just like a normal method call by main thread. Hence Multithreading won't be there.
  • 13. Case 2: A thread cannot be started twice. If you try to do so, IllegalThreadStateException will be thrown. Class Test { public static void main(String args[]) { Mythread t=new Mythread(); t.start(); t.start();//Exception thrown } }
  • 14. By implementing Runnable interface Class MyRunnable implements Runnable { public void run() { for(int i=0;i<10;i++) { System.out.println(“child thread”); } } }
  • 15. Class ThreadDemo { public static void main(String args[]) { MyRunnable r=new MyRunnable(); Thread t=new Thread(r); t.start(); for(int i=0;i<10;i++) { System.out.println(“main thread”); } } }
  • 16. MyRunnable r=new MyRunnable(); Thread t=new Thread(); Thread t1=new Thread(r); Case1: t.start(); ->it execute thread run method. Case 2:t.run();-> it executes thread run method. Case3:t1.start();->it execute runnable run method Case4:t1.run();->it executes runnable run method without creating thread. Case 5:r.start();->compile time error. Case6: r.run();-> it executes runnable run method without creating thread.
  • 17. Getting and setting name of thread Every thread in java has some name. it may be default name generated by JVM or Customized name provided by programmer. We can get and set the name of a thread by using the following two methods of thread class. 1.Public final String getName() 2.Public final void setName(String name)
  • 18. Example Class MyThread extends Thread { } Class Test { public static void main(String args[]) { System.out.println(Thread.currentThread().getName()); MyThraed t=new MyThread(); System.out.println(t.getName()); Thread.currentThread().setName(“CMR”); System.out.println(Thread.currentThread().getName()); } }
  • 19. Creating Multiple Threads class NewThread implements Runnable { String name; // name of thread Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); //System.out.println("New thread: " + t); t.start(); // Start the thread } public void run() { try { for (int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name + "Interrupted"); } System.out.println(name + " exiting."); } }
  • 20. class MultiThreadDemo { public static void main(String args[]) { new NewThread("One"); // start threads new NewThread("Two"); new NewThread("Three"); try { Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Main thread exiting."); } }
  • 21. Thread Priorities Every thread in java has some priority it may be default priority generated by JVM or customized priority provided by programmer The valid range of thread priorities is 1 to 10. where 1—MIN_PRIORITY 10---MAX_PRIORITY Thread class defines the following constants to represent some standard priorities Thread.MIN_PRIORITY------1 Thread.NORM_PRIORITY-----5 Thraed.MAX_PRIORITY---------10
  • 22. Thread scheduler will use priorities while allocating processor. The Thread which is having highest priority will get chance first. If two threads having same priority then we can’t except exact execution order. it depends on thread scheduler. Thread class defines the following methods to get and set priority of a thread. public final int getPriority(). Public final void setPriority(int p)
  • 23. Default Priority The default priority only for the main thread is 5. But for all remaining threads default priority will be inherited form parent to child. i.e what ever priority parent thread has the same priority will be there for the child thread.
  • 24. Example: Class Mythread extends Thread { } Class thredDemo { Public static void main(String args[]) { System.out.println(Thread.currentThread().getPriority()); //Thread.currentThread().setPriority(8); Mythread t=new Mythread(); System.out.println(t.getPriority()); } }
  • 25. Setting the thread Priority class Mythread extends Thread { public void run() { for(int i=0;i<10;i++) { System.out.println("Child thread"); } } }
  • 26. class ThredPriorityDemo1 { public static void main(String args[]) { Mythread t=new Mythread(); t.setPriority(10); t.start(); for(int i=0;i<10;i++) { System.out.println("Main thread"); } } } Output Child thread –10 times Main thread—10 times note Some platforms won’t provide support for thread priorities.
  • 27. important methods of thread class To prevent a thread execution the following methods are used. 1.yield() 2.join() 3.sleep()
  • 28. Yield() Yield method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. Syntax Public static native void yield()
  • 29. Example Class mythread extends Thread { Public void run() { For(int i=0;i<10;i++) { System.out.println(“child thread”); Thread.yield(); } } } Class ThreadYieldDemo { Public sataic void main(String args[]) { Mythread t=new Mythread(); t.strat(); for(int i=0;i<10;i++) { System.out.println(“main thread”); } } }
  • 30. Join () If a thread wants to wait until completing some other thread then we should go for join() method. example If a thread T1 wants to wait until completing T2 then T1 has to call T2.join().If T1 executes T2.join() then immediately T1 will be entered into waiting state until T2 completes. Once T2 completes then T1 can continue its execution. Syntax Public final void join() throws InterruptedException Public final void join(long ms) throws InterruptedException Public final void join(long ms, int ns) throws InterruptedException
  • 31. Example class Mythread extends Thread { public void ru() { for(int i=0;i<10;i++) { System.out.println("seetha Thread"); try { Thread.sleep(2000); } catch(InterruptedException e) { } } } } class ThreadJoinDemo { public static void main(String args[])throws InterruptedException { Mythread t=new Mythread(); t.start(); t.join(); for(int i=0;i<10;i++) { System.out.println("rama Thread"); } } }
  • 32. Sleep () If a thread don’t want to perform any operation per a particular amount of time then we should go for sleep() method. Syntax Public static native void sleep(long ms) throws InterruptedException Public static void sleep(long ms, int ns) throws InterruptedException
  • 33. Example class SlideRotator { public static void main(String args[])throws InterruptedException { for(int i=0;i<10;i++) { System.out.println("Slide:"+i); Thread.sleep(5000); } } }