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
 
Ad

More Related Content

What's hot (19)

Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
Appsterdam Milan
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
Arun Mehra
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-java
aalipalh
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
Arvind Krishnaa
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Lovely Professional University
 
Thread
ThreadThread
Thread
Juhi Kumari
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
Hemo Chella
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton Keks
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Java threading
Java threadingJava threading
Java threading
Chinh Ngo Nguyen
 
Multi threading
Multi threadingMulti threading
Multi threading
gndu
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
javathreads
javathreadsjavathreads
javathreads
Arjun Shanka
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
Hitendra Kumar
 
Multi threading
Multi threadingMulti threading
Multi threading
Mavoori Soshmitha
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
Arun Mehra
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-java
aalipalh
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton Keks
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Multi threading
Multi threadingMulti threading
Multi threading
gndu
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
Hitendra Kumar
 

Viewers also liked (20)

HTML5 Multithreading
HTML5 MultithreadingHTML5 Multithreading
HTML5 Multithreading
Allan Huang
 
글로벌 사업PM 직무 면접 준비용 신규 사업 제안서
글로벌 사업PM 직무 면접 준비용 신규 사업 제안서글로벌 사업PM 직무 면접 준비용 신규 사업 제안서
글로벌 사업PM 직무 면접 준비용 신규 사업 제안서
ByungKon (Alvin) Lee
 
Group 2 - Women in the European Workplace
Group 2 - Women in the European WorkplaceGroup 2 - Women in the European Workplace
Group 2 - Women in the European Workplace
Rosa Panadero, MBA روسا باناديرو، ماجستير الإدارة العالمية
 
Features of java technology
Features of java technologyFeatures of java technology
Features of java technology
Prognoz Technologies Pvt. Ltd.
 
Examen robalino 2_a
Examen robalino 2_aExamen robalino 2_a
Examen robalino 2_a
Mady Robalino
 
Trabajo catálogo
 Trabajo catálogo  Trabajo catálogo
Trabajo catálogo
José Alberto Alonso Gallardo
 
Godrej properties limited
Godrej properties limitedGodrej properties limited
Godrej properties limited
pooja Devi(Guru Nanak dev University)
 
cloud computing
 cloud computing cloud computing
cloud computing
pooja Devi(Guru Nanak dev University)
 
Trabajo empreneduria
Trabajo empreneduriaTrabajo empreneduria
Trabajo empreneduria
Juan Muñoz
 
William Gleason CV OCT 2016
William Gleason CV  OCT 2016William Gleason CV  OCT 2016
William Gleason CV OCT 2016
William Gleason
 
Sarathi_Resume_June 2016
Sarathi_Resume_June 2016Sarathi_Resume_June 2016
Sarathi_Resume_June 2016
Sarathi Thangavel
 
How does my horror film challenges forms and
How does my horror film challenges forms andHow does my horror film challenges forms and
How does my horror film challenges forms and
Harry Dosher
 
Ricky ortegon
Ricky ortegonRicky ortegon
Ricky ortegon
Ricky ortegon
 
Object-Oriented Paradigm
Object-Oriented Paradigm Object-Oriented Paradigm
Object-Oriented Paradigm
tamigayle
 
Internet of Things: How To Start
Internet of Things: How To StartInternet of Things: How To Start
Internet of Things: How To Start
msyukor
 
First Solar Buy CTC
First Solar Buy CTCFirst Solar Buy CTC
First Solar Buy CTC
Allison Rhodes
 
Async IO and Multithreading explained
Async IO and Multithreading explainedAsync IO and Multithreading explained
Async IO and Multithreading explained
Directi Group
 
Dockerizing IoT Services
Dockerizing IoT ServicesDockerizing IoT Services
Dockerizing IoT Services
msyukor
 
PROJECT AMUL
PROJECT AMULPROJECT AMUL
PROJECT AMUL
Prathamesh Narkar
 
Database connectivity and web technologies
Database connectivity and web technologiesDatabase connectivity and web technologies
Database connectivity and web technologies
Dhani Ahmad
 
HTML5 Multithreading
HTML5 MultithreadingHTML5 Multithreading
HTML5 Multithreading
Allan Huang
 
글로벌 사업PM 직무 면접 준비용 신규 사업 제안서
글로벌 사업PM 직무 면접 준비용 신규 사업 제안서글로벌 사업PM 직무 면접 준비용 신규 사업 제안서
글로벌 사업PM 직무 면접 준비용 신규 사업 제안서
ByungKon (Alvin) Lee
 
Trabajo empreneduria
Trabajo empreneduriaTrabajo empreneduria
Trabajo empreneduria
Juan Muñoz
 
William Gleason CV OCT 2016
William Gleason CV  OCT 2016William Gleason CV  OCT 2016
William Gleason CV OCT 2016
William Gleason
 
How does my horror film challenges forms and
How does my horror film challenges forms andHow does my horror film challenges forms and
How does my horror film challenges forms and
Harry Dosher
 
Object-Oriented Paradigm
Object-Oriented Paradigm Object-Oriented Paradigm
Object-Oriented Paradigm
tamigayle
 
Internet of Things: How To Start
Internet of Things: How To StartInternet of Things: How To Start
Internet of Things: How To Start
msyukor
 
Async IO and Multithreading explained
Async IO and Multithreading explainedAsync IO and Multithreading explained
Async IO and Multithreading explained
Directi Group
 
Dockerizing IoT Services
Dockerizing IoT ServicesDockerizing IoT Services
Dockerizing IoT Services
msyukor
 
Database connectivity and web technologies
Database connectivity and web technologiesDatabase connectivity and web technologies
Database connectivity and web technologies
Dhani Ahmad
 
Ad

Similar to Md09 multithreading (20)

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
Himanshu Rajput
 
Java
JavaJava
Java
mdfkhan625
 
multithreading
multithreadingmultithreading
multithreading
Rajkattamuri
 
Multithreading
MultithreadingMultithreading
Multithreading
F K
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
Mohammed625
 
Java
JavaJava
Java
Khasim Cise
 
Multithreading
MultithreadingMultithreading
Multithreading
backdoor
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
talha ijaz
 
Multithreading
MultithreadingMultithreading
Multithreading
sagsharma
 
Concept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptxConcept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
Threads and Synchronization in c#
Threads and Synchronization in c#Threads and Synchronization in c#
Threads and Synchronization in c#
Rizwan Ali
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
HarshaDokula
 
Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#
Rizwan Ali
 
this power point presentation is about concurrency and multithreading
this power point presentation is about concurrency and multithreadingthis power point presentation is about concurrency and multithreading
this power point presentation is about concurrency and multithreading
Betty333100
 
Multithreading
MultithreadingMultithreading
Multithreading
Ravi Chythanya
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Multithreading
MultithreadingMultithreading
Multithreading
F K
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
Mohammed625
 
Multithreading
MultithreadingMultithreading
Multithreading
backdoor
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
talha ijaz
 
Multithreading
MultithreadingMultithreading
Multithreading
sagsharma
 
Concept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptxConcept of Java Multithreading-Partially.pptx
Concept of Java Multithreading-Partially.pptx
SahilKumar542
 
Threads and Synchronization in c#
Threads and Synchronization in c#Threads and Synchronization in c#
Threads and Synchronization in c#
Rizwan Ali
 
Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#
Rizwan Ali
 
this power point presentation is about concurrency and multithreading
this power point presentation is about concurrency and multithreadingthis power point presentation is about concurrency and multithreading
this power point presentation is about concurrency and multithreading
Betty333100
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Ad

More from Rakesh Madugula (13)

New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
Rakesh Madugula
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
Rakesh Madugula
 
Md121 streams
Md121 streamsMd121 streams
Md121 streams
Rakesh Madugula
 
Md11 gui event handling
Md11 gui event handlingMd11 gui event handling
Md11 gui event handling
Rakesh Madugula
 
Md10 building java gu is
Md10 building java gu isMd10 building java gu is
Md10 building java gu is
Rakesh Madugula
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
Rakesh Madugula
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 
Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class features
Rakesh Madugula
 
Md05 arrays
Md05 arraysMd05 arrays
Md05 arrays
Rakesh Madugula
 
Md04 flow control
Md04 flow controlMd04 flow control
Md04 flow control
Rakesh Madugula
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
Rakesh Madugula
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
Rakesh Madugula
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting Started
Rakesh Madugula
 

Recently uploaded (20)

GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 

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.