SlideShare a Scribd company logo
  Threads and Multithreading
  Objectives •  Define a thread.  •  Create separate threads in a Java technology program,  controlling the code and data that are used by that thread.  •  Control the execution of a thread and write platform­ independent  code with threads. •  Describe the difficulties that might arise when multiple threads  share data.  •  Use wait and notify to communicate between threads.  •  Use synchronized to protect data from corruption.
Sequential program Sequential program   ,means having  beginning   a  execution sequence  and an  end.   Thread Thread  is similar to sequential program, it has  beginning  , an  execution sequence  and an  end, thread itself is not a program as it cannot run on its own, rather it runs within a program.
The real advantage threading is not to have a single  sequential thread , rather its about the use of multiple  thread running at the same time and performing  different tasks in a single program.
Multithreading The ability of an  operating system  to  execute different  parts of a program , called  threads,  simultaneously . (illusion actually there are certain scheduling algorithm that  needs to be followed)  The programmer must carefully design the program in such a  way that all the threads can run at the same time without  interfering with each other.
Example  :- Web browser   Scroll a page  while its  downloading an applet   Play animation and sound concurrently   Print a page in the background
Multitasking The ability to execute more than one task at the  same time.  The terms multitasking and multiprocessing are often  used interchangeably.  Although multiprocessing implies that more than one CPU is involved.  In multitasking, only one CPU is involved, but it switches  from one program to another so quickly that it gives  the appearance of executing all of the programs at the  same time.
Two  distinct  types of multitasking :  Process-based  Thread-based.
Process-based   multitasking   is the feature that allows your computer to run  two or more programs concurrently.  For example , process-based multitasking enables you to  run the Java compiler at the same time that you are  using a text editor.
Thread-based   multitasking The thread is the smallest unit of dispatchable code. A single program can perform two or more tasks simultaneously. For example , a text editor can format text at the same time  that it is printing, as long as these two actions are being  performed by two separate threads.
Thread Priorities Every  thread  has a  priority , Thread with higher  priority are executed in preference to threads with  lower priority,when code running in some thread  creates a new Thread object , the new thread has its  priority initially set equal to the priority of creating  thread. Setting the priority of a thread FooRunnable r = new FooRunnable(); Thread t = new Thread(r); t.setPriority(8); t.start();
Remember Thread.MIN_PRIORITY (1) Thread.NORM_PRIORITY (5) Thread.MAX_PRIORITY (10)
Two ways to create new thread of execution  1.Declare a class to be subclass of Thread, this subclass  should override the run method of class Thread.   Example   ( ExtendThread.java ) class PrimeThread extends Thread { long minPrime; PrimeThread(long minPrime) { this.minPrime = minPrime;  }  public void run() { // compute primes larger than minPrime  }  }
2.Declare a class that implements the Runnable interface,  that class then implements the run method   Example   (ThreadDemo.java) class PrimeRun implements Runnable { long minPrime;  PrimeRun(long minPrime) { this.minPrime = minPrime;  }  public void run() { // compute primes larger than minPrime    }  }
In both cases  then create a thread and start it running:  PrimeThread p = new PrimeThread(143);  p.start();   If a class must subclass some other class use  Runnable  as  in case of applets  ,since a class  cannot be a subclass of both Thread and Applet , Thus the class use the Runnable interface.
The Main Thread When a Java program starts up, one thread begins  running immediately. This is usually called the main thread of your program. The main thread is important for two reasons: ■  It is the thread from which other “child” threads  will be spawned. ■  Often it must be the last thread to finish execution  because it performs various shutdown actions.
Life cycle of Thread
New Thread Thread clockThread= new Thread(this, “Clock”);  //new Thread(Runnable Target, String name) After this statement is executed clockThread is in New  Thread state. Thread in this state is merely an empty Thread object , no system resources have been allocated for it yet. At this stage the thread is not considered to be alive. When the thread is in this state we can only start the thread. Calling any other method besides start , cause  IllegalThreadStateException.
Runnable clockThread.start(); This is the state a thread is in when it's eligible to run, but the scheduler has not selected it to be the running thread.  A thread first enters the runnable state when the start()  method is invoked, but a thread can also return to the runnable  state after either running or coming back from a blocked, waiting,  or sleeping state.  When the thread is in the runnable state,it is considered  alive .
Running This is the state a thread is in when the thread scheduler  selects it (from the runnable pool) to be the currently executing  process. A thread can transition out of a running state for several  reasons,
Not Runnable To make a thread not runnable   * Its sleep method is invoked * The thread call the wait method to wait for specific  condition to be satisfied * The thread is blocking on IO
Not Runnable to Runnable Exit for every entrance to Not Runnable state If the thread is put to sleep , the specified number of  milliseconds must elapse. If the thread is waiting for a condition,then another  object must notify the waiting thread of a change in  condition by calling notify or notifyAll. If the thread is blocked on I/O, the I/O must complete.   Stop Thread stops when the run method terminates.
Testing Thread States  Thread.getState() method return one of the thread  states NEW  RUNNABLE  BLOCKED  WAITING  TERMINATED isAlive() method returns true if thread has been  started and not stopped  (when it is either Runnable or Not Runnable) isAlive() returns false if thread is a New Thread or  is Dead
How to cause the thread to execute from a class that implements  Runnable? class MyClass implements Runnable {   public void run() { for(int x =1; x < 6; x++) { System.out.println(&quot;Runnable running&quot;); } } } Is this right to cause the thread to execute?  Runnable r = new Runnable(); r.run();
Remember, every thread of execution begins as an instance of  class Thread.Regardless of whether your run() method is in a  Thread subclass or a Runnable implementation class, you still need  a Thread object to do the work. MyClass mc = new MyClass(); Thread t = new Thread(mc); t.start(); Although it is the run method code that executes, a thread is actually  started via the start method
Thread Scheduling  Execution of multiple threads on a single CPU in  some order is called  scheduling. JRE support a very simple scheduling algorithms  called  Fixed priority scheduling. Time Slicing scheduling.   When a thread is created, it inherit its property from  the thread that created it ,modify the thread priority  at any time by using setPriority method.
Relinquishing the CPU A thread can voluntarily yield the CPU by calling the  yield  method. The  yield  method gives other threads of the  same priority a chance to run. If no equal-priority threads  are Runnable, the  yield  is ignored.
Is it possible to overload the run() method in your Thread subclass? class MyThread extends Thread { public void run() { System.out.println(&quot;Important job running in MyThread&quot;); } public void run(String s) { System.out.println(&quot;String in run is &quot; + s); } }
The overloaded run(String s) method will be ignored by the Thread class unless you call it yourself. The Thread class expects a  run() method with no arguments, and it will execute this method for  you in a separate call stack after the thread has been started. With a run(String s) method, execution won't happen in a  new thread of execution with a separate call stack. It will just happen  in the same call stack as the code that you made the call from, just  like any other normal method call.
 
Synchronizing Threads Imagine an application in which one thread write  data to a file while second thread read data from the  same file, as the thread share a common resource (file) they must be synchronized. Example ProducerConsumer.java Producer generates an integer between 0 and 9, store it in CubbyHole object Consumer consumes all integer from the CubbyHole  as quickly as they become available
Race Condition One   problem  arises when the  Producer  is quicker than  the  Consumer  and generates two numbers before the  Consumer  has a chance to consume the first one Another problem  might arise when the  Consumer  is  quicker than the  Producer  and consumes the same value  twice. In this situation, the  Consumer  might produce  output that looks like this:
A  race condition  is a situation in which two or more  threads or processes are reading or writing some shared  data, and the final result depends on the timing of how  the threads are scheduled,
Race condition  can be  prevented  by  1.Synchronizing the storage and retrieval of integer. 2. Second, the two threads must do some simple  coordination. That is, the  Producer  must have a way to  indicate to the  Consumer  that the value is ready, and  the  Consumer  must have a way to indicate that the  value has been retrieved. The  Object  class provides  a collection of methods —  wait ,  notify , and  notify All Note  You can easily wake up wait with a notify but a  sleeping thread cannot be awakened prematurely before  the specified time elapse.
Starvation & Deadlock  Starvation occurs when one or more threads in your  program  are blocked from gaining access to a resource,  and deadlock in one of the ultimate form of starvation  when two or more threads are waiting for the other to  do something.  Example DeadLockExample
Other Examples Using isAlive( ) and join( )  DemoJoin.java   Thread Priority  HiLoPri.java
 

More Related Content

PPTX
Multithreading in java
PPT
Java Multithreading
PPT
Basic of Multithreading in JAva
PPTX
Multi-threaded Programming in JAVA
PPT
Java Multithreading and Concurrency
PPTX
Advanced Introduction to Java Multi-Threading - Full (chok)
PPTX
Multithread Programing in Java
PPTX
Multithreading programming in java
Multithreading in java
Java Multithreading
Basic of Multithreading in JAva
Multi-threaded Programming in JAVA
Java Multithreading and Concurrency
Advanced Introduction to Java Multi-Threading - Full (chok)
Multithread Programing in Java
Multithreading programming in java

What's hot (19)

PDF
Multithreading in Java
PDF
Java Multithreading Using Executors Framework
PPSX
Multithreading in-java
PPTX
Multithreading in java
PDF
Java Thread Synchronization
ODP
Multithreading Concepts
ODP
Multithreading In Java
PPTX
Multithreading in java
PPT
Thread
PPT
Chap2 2 1
PDF
Java Course 10: Threads and Concurrency
PPT
Java multi threading
PDF
Java threading
PPTX
Multi threading
PPTX
MULTI THREADING IN JAVA
PDF
javathreads
PPT
Java And Multithreading
PPT
Java Performance, Threading and Concurrent Data Structures
PPTX
Multi threading
Multithreading in Java
Java Multithreading Using Executors Framework
Multithreading in-java
Multithreading in java
Java Thread Synchronization
Multithreading Concepts
Multithreading In Java
Multithreading in java
Thread
Chap2 2 1
Java Course 10: Threads and Concurrency
Java multi threading
Java threading
Multi threading
MULTI THREADING IN JAVA
javathreads
Java And Multithreading
Java Performance, Threading and Concurrent Data Structures
Multi threading
Ad

Viewers also liked (20)

PPT
HTML5 Multithreading
PDF
글로벌 사업PM 직무 면접 준비용 신규 사업 제안서
PPSX
Features of java technology
PPTX
Examen robalino 2_a
PDF
Trabajo catálogo
DOCX
Godrej properties limited
PPTX
Trabajo empreneduria
PDF
William Gleason CV OCT 2016
DOCX
Sarathi_Resume_June 2016
PPTX
How does my horror film challenges forms and
PPTX
Ricky ortegon
PPTX
Object-Oriented Paradigm
PPTX
Internet of Things: How To Start
PPTX
First Solar Buy CTC
PPT
Async IO and Multithreading explained
PDF
Dockerizing IoT Services
DOCX
PROJECT AMUL
PPT
Database connectivity and web technologies
HTML5 Multithreading
글로벌 사업PM 직무 면접 준비용 신규 사업 제안서
Features of java technology
Examen robalino 2_a
Trabajo catálogo
Godrej properties limited
Trabajo empreneduria
William Gleason CV OCT 2016
Sarathi_Resume_June 2016
How does my horror film challenges forms and
Ricky ortegon
Object-Oriented Paradigm
Internet of Things: How To Start
First Solar Buy CTC
Async IO and Multithreading explained
Dockerizing IoT Services
PROJECT AMUL
Database connectivity and web technologies
Ad

Similar to Md09 multithreading (20)

PPTX
Multithreading
DOCX
Threadnotes
PPTX
MSBTE Computer Engineering JPR java. multi. threading.pptx
PPTX
PPTX
Chap3 multi threaded programming
PDF
Multithreading Introduction and Lifecyle of thread
PDF
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
PPTX
Multithreading in java
PPTX
Multithreading in java
PPTX
econtent thread in java.pptx
PPT
PPT
Multithreading
 
PPT
multithreading
PPT
JAVA MULTITHREDED PROGRAMMING - LECTURES
PPT
Java multithreading
PPT
Threads in java, Multitasking and Multithreading
PPTX
multithreading to be used in java with good programs.pptx
PPTX
multithreading.pptx
PPT
PPT
Threads in Java
Multithreading
Threadnotes
MSBTE Computer Engineering JPR java. multi. threading.pptx
Chap3 multi threaded programming
Multithreading Introduction and Lifecyle of thread
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
Multithreading in java
Multithreading in java
econtent thread in java.pptx
Multithreading
 
multithreading
JAVA MULTITHREDED PROGRAMMING - LECTURES
Java multithreading
Threads in java, Multitasking and Multithreading
multithreading to be used in java with good programs.pptx
multithreading.pptx
Threads in Java

More from Rakesh Madugula (13)

PPT
New features and enhancement
PPT
Md13 networking
PPT
Md121 streams
PPT
Md11 gui event handling
PPT
Md10 building java gu is
PPT
Md08 collection api
PPT
Md07 exceptions&assertion
PPT
Md06 advance class features
PPT
Md05 arrays
PPT
Md04 flow control
PPT
Md03 - part3
PPT
Md02 - Getting Started part-2
PPT
A begineers guide of JAVA - Getting Started
New features and enhancement
Md13 networking
Md121 streams
Md11 gui event handling
Md10 building java gu is
Md08 collection api
Md07 exceptions&assertion
Md06 advance class features
Md05 arrays
Md04 flow control
Md03 - part3
Md02 - Getting Started part-2
A begineers guide of JAVA - Getting Started

Recently uploaded (20)

PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
master seminar digital applications in india
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Complications of Minimal Access Surgery at WLH
PDF
RMMM.pdf make it easy to upload and study
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Cell Types and Its function , kingdom of life
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Lesson notes of climatology university.
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Basic Mud Logging Guide for educational purpose
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Pharma ospi slides which help in ospi learning
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
O7-L3 Supply Chain Operations - ICLT Program
master seminar digital applications in india
VCE English Exam - Section C Student Revision Booklet
Complications of Minimal Access Surgery at WLH
RMMM.pdf make it easy to upload and study
Microbial disease of the cardiovascular and lymphatic systems
PPH.pptx obstetrics and gynecology in nursing
Abdominal Access Techniques with Prof. Dr. R K Mishra
Cell Types and Its function , kingdom of life
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Lesson notes of climatology university.
Anesthesia in Laparoscopic Surgery in India
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
TR - Agricultural Crops Production NC III.pdf
Basic Mud Logging Guide for educational purpose
GDM (1) (1).pptx small presentation for students
Pharma ospi slides which help in ospi learning

Md09 multithreading

  • 1. Threads and Multithreading
  • 2. Objectives • Define a thread. • Create separate threads in a Java technology program, controlling the code and data that are used by that thread. • Control the execution of a thread and write platform­ independent code with threads. • Describe the difficulties that might arise when multiple threads share data. • Use wait and notify to communicate between threads. • Use synchronized to protect data from corruption.
  • 3. Sequential program Sequential program ,means having beginning a execution sequence and an end. Thread Thread is similar to sequential program, it has beginning , an execution sequence and an end, thread itself is not a program as it cannot run on its own, rather it runs within a program.
  • 4. The real advantage threading is not to have a single sequential thread , rather its about the use of multiple thread running at the same time and performing different tasks in a single program.
  • 5. Multithreading The ability of an operating system to execute different parts of a program , called threads, simultaneously . (illusion actually there are certain scheduling algorithm that needs to be followed) The programmer must carefully design the program in such a way that all the threads can run at the same time without interfering with each other.
  • 6. Example :- Web browser Scroll a page while its downloading an applet Play animation and sound concurrently Print a page in the background
  • 7. Multitasking The ability to execute more than one task at the same time. The terms multitasking and multiprocessing are often used interchangeably. Although multiprocessing implies that more than one CPU is involved. In multitasking, only one CPU is involved, but it switches from one program to another so quickly that it gives the appearance of executing all of the programs at the same time.
  • 8. Two distinct types of multitasking : Process-based Thread-based.
  • 9. Process-based multitasking is the feature that allows your computer to run two or more programs concurrently. For example , process-based multitasking enables you to run the Java compiler at the same time that you are using a text editor.
  • 10. Thread-based multitasking The thread is the smallest unit of dispatchable code. A single program can perform two or more tasks simultaneously. For example , a text editor can format text at the same time that it is printing, as long as these two actions are being performed by two separate threads.
  • 11. Thread Priorities Every thread has a priority , Thread with higher priority are executed in preference to threads with lower priority,when code running in some thread creates a new Thread object , the new thread has its priority initially set equal to the priority of creating thread. Setting the priority of a thread FooRunnable r = new FooRunnable(); Thread t = new Thread(r); t.setPriority(8); t.start();
  • 12. Remember Thread.MIN_PRIORITY (1) Thread.NORM_PRIORITY (5) Thread.MAX_PRIORITY (10)
  • 13. Two ways to create new thread of execution 1.Declare a class to be subclass of Thread, this subclass should override the run method of class Thread. Example ( ExtendThread.java ) class PrimeThread extends Thread { long minPrime; PrimeThread(long minPrime) { this.minPrime = minPrime; } public void run() { // compute primes larger than minPrime } }
  • 14. 2.Declare a class that implements the Runnable interface, that class then implements the run method   Example (ThreadDemo.java) class PrimeRun implements Runnable { long minPrime; PrimeRun(long minPrime) { this.minPrime = minPrime; } public void run() { // compute primes larger than minPrime   } }
  • 15. In both cases then create a thread and start it running: PrimeThread p = new PrimeThread(143); p.start(); If a class must subclass some other class use Runnable as in case of applets ,since a class cannot be a subclass of both Thread and Applet , Thus the class use the Runnable interface.
  • 16. The Main Thread When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program. The main thread is important for two reasons: ■ It is the thread from which other “child” threads will be spawned. ■ Often it must be the last thread to finish execution because it performs various shutdown actions.
  • 17. Life cycle of Thread
  • 18. New Thread Thread clockThread= new Thread(this, “Clock”); //new Thread(Runnable Target, String name) After this statement is executed clockThread is in New Thread state. Thread in this state is merely an empty Thread object , no system resources have been allocated for it yet. At this stage the thread is not considered to be alive. When the thread is in this state we can only start the thread. Calling any other method besides start , cause IllegalThreadStateException.
  • 19. Runnable clockThread.start(); This is the state a thread is in when it's eligible to run, but the scheduler has not selected it to be the running thread. A thread first enters the runnable state when the start() method is invoked, but a thread can also return to the runnable state after either running or coming back from a blocked, waiting, or sleeping state. When the thread is in the runnable state,it is considered alive .
  • 20. Running This is the state a thread is in when the thread scheduler selects it (from the runnable pool) to be the currently executing process. A thread can transition out of a running state for several reasons,
  • 21. Not Runnable To make a thread not runnable * Its sleep method is invoked * The thread call the wait method to wait for specific condition to be satisfied * The thread is blocking on IO
  • 22. Not Runnable to Runnable Exit for every entrance to Not Runnable state If the thread is put to sleep , the specified number of milliseconds must elapse. If the thread is waiting for a condition,then another object must notify the waiting thread of a change in condition by calling notify or notifyAll. If the thread is blocked on I/O, the I/O must complete. Stop Thread stops when the run method terminates.
  • 23. Testing Thread States Thread.getState() method return one of the thread states NEW RUNNABLE BLOCKED WAITING TERMINATED isAlive() method returns true if thread has been started and not stopped (when it is either Runnable or Not Runnable) isAlive() returns false if thread is a New Thread or is Dead
  • 24. How to cause the thread to execute from a class that implements Runnable? class MyClass implements Runnable { public void run() { for(int x =1; x < 6; x++) { System.out.println(&quot;Runnable running&quot;); } } } Is this right to cause the thread to execute? Runnable r = new Runnable(); r.run();
  • 25. Remember, every thread of execution begins as an instance of class Thread.Regardless of whether your run() method is in a Thread subclass or a Runnable implementation class, you still need a Thread object to do the work. MyClass mc = new MyClass(); Thread t = new Thread(mc); t.start(); Although it is the run method code that executes, a thread is actually started via the start method
  • 26. Thread Scheduling  Execution of multiple threads on a single CPU in some order is called scheduling. JRE support a very simple scheduling algorithms called Fixed priority scheduling. Time Slicing scheduling. When a thread is created, it inherit its property from the thread that created it ,modify the thread priority at any time by using setPriority method.
  • 27. Relinquishing the CPU A thread can voluntarily yield the CPU by calling the yield method. The yield method gives other threads of the same priority a chance to run. If no equal-priority threads are Runnable, the yield is ignored.
  • 28. Is it possible to overload the run() method in your Thread subclass? class MyThread extends Thread { public void run() { System.out.println(&quot;Important job running in MyThread&quot;); } public void run(String s) { System.out.println(&quot;String in run is &quot; + s); } }
  • 29. The overloaded run(String s) method will be ignored by the Thread class unless you call it yourself. The Thread class expects a run() method with no arguments, and it will execute this method for you in a separate call stack after the thread has been started. With a run(String s) method, execution won't happen in a new thread of execution with a separate call stack. It will just happen in the same call stack as the code that you made the call from, just like any other normal method call.
  • 30.  
  • 31. Synchronizing Threads Imagine an application in which one thread write data to a file while second thread read data from the same file, as the thread share a common resource (file) they must be synchronized. Example ProducerConsumer.java Producer generates an integer between 0 and 9, store it in CubbyHole object Consumer consumes all integer from the CubbyHole as quickly as they become available
  • 32. Race Condition One problem arises when the Producer is quicker than the Consumer and generates two numbers before the Consumer has a chance to consume the first one Another problem might arise when the Consumer is quicker than the Producer and consumes the same value twice. In this situation, the Consumer might produce output that looks like this:
  • 33. A race condition is a situation in which two or more threads or processes are reading or writing some shared data, and the final result depends on the timing of how the threads are scheduled,
  • 34. Race condition can be prevented by 1.Synchronizing the storage and retrieval of integer. 2. Second, the two threads must do some simple coordination. That is, the Producer must have a way to indicate to the Consumer that the value is ready, and the Consumer must have a way to indicate that the value has been retrieved. The Object class provides a collection of methods — wait , notify , and notify All Note You can easily wake up wait with a notify but a sleeping thread cannot be awakened prematurely before the specified time elapse.
  • 35. Starvation & Deadlock Starvation occurs when one or more threads in your program are blocked from gaining access to a resource, and deadlock in one of the ultimate form of starvation when two or more threads are waiting for the other to do something. Example DeadLockExample
  • 36. Other Examples Using isAlive( ) and join( ) DemoJoin.java Thread Priority HiLoPri.java
  • 37.