SlideShare une entreprise Scribd logo
1  sur  38
Threads
Java Threads A thread is not an object A thread is a flow of control A thread is a series of executed statements A thread is a nested sequence of method calls
The Thread Object A thread is not an object A Thread is an object void start() Creates a new thread and makes it runnable void run() The new thread begins its life inside this method
Thread Creation Diagram Object A Object BThread (extends Thread)  Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { 	// create thread } void run() { 	doSomething(); }
Thread Creation Diagram Object A Object BThread (extends Thread)  Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { 	// create thread } void run() { 	doSomething(); }
Thread Creation Diagram Object A Object BThread (extends Thread)  Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { 	// create thread } void run() { 	doSomething(); }
Thread Creation Diagram Object A Object BThread (extends Thread)  Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { 	// create thread } void run() { 	doSomething(); }
Thread Creation Diagram Object A Object BThread (extends Thread)  Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { 	// create thread } void run() { 	doSomething(); }
Thread Creation Diagram Object A Object BThread (extends Thread)  Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { 	// create thread } void run() { 	doSomething(); }
Thread Creation Diagram Object A Object BThread (extends Thread)  Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { 	// create thread } void run() { 	doSomething(); }
Thread Creation Diagram Object A Object BThread (extends Thread)  Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { 	// create thread } void run() { 	doSomething(); }
Thread Creation Diagram Object A Object BThread (extends Thread)  Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { 	// create thread } void run() { 	doSomething(); }
Runnable Interface A helper to the thread object The Thread object’s run() method calls the Runnable object’s run() method Allows threads to run inside any object, regardless of inheritance
Runnable Example Talker talker = new Talker(); Thread t = new Thread(talker); t.Start(); --- class Talker implements Runnable {   public void run() {     while (true) {        System.out.println(“yakitty yak”);      }   } }
Thread Lifecycle Active sleep(500) Blocked wake up Born JVM start() suspend() Runnable resume() stop() wait stop() notify Dead block on I/O I/O available
Blocking Threads When reading from a stream, if input is not available, the thread will block Thread is suspended (“blocked”) until I/O is available Allows other threads to automatically activate When I/O available, thread wakes back up again Becomes “runnable” Not to be confused with the Runnable interface
Thread Scheduling In general, the runnable thread with the highest priority is active (running) Java is priority-preemptive If a high-priority thread wakes up, and a low-priority thread is running Then the high-priority thread gets to run immediately Allows on-demand processing Efficient use of CPU
Thread Starvation If a high priority thread never blocks Then all other threads will starve Must be clever about thread priority
Thread Priorities: General Strategies Threads that have more to do should get lower priority Counterintuitive Cut to head of line for short tasks Give your I/O-bound threads high priority Wake up, immediately process data, go back to waiting for I/O
Thread Synchronization Language keyword: synchronized Takes out a monitor lock on an object Exclusive lock for that thread If lock is currently unavailable, thread will block
Thread Synchronization Protects access to code, not to data Make data members private Synchronize accessor methods Puts a “force field” around the locked object so no other threads can enter Actually, it only blocks access to other synchronizing threads
Wait and Notify Allows two threads to cooperate Based on a single shared lock object
Wait and Notify: Code Consumer: synchronized (lock) {   while (!resourceAvailable()) {     lock.wait();   }   consumeResource(); }
Wait and Notify: Code Producer: produceResource(); synchronized (lock) {   lock.notifyAll(); }
Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2.   lock.wait(); 5.   lock.notify(); 9.   consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2.   lock.wait(); 5.   lock.notify(); 9.   consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2.   lock.wait(); 5.   lock.notify(); 9.   consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2.   lock.wait(); 5.   lock.notify(); 9.   consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2.   lock.wait(); 5.   lock.notify(); 9.   consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2.   lock.wait(); 5.   lock.notify(); 9.   consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2.   lock.wait(); 5.   lock.notify(); 9.   consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2.   lock.wait(); 5.   lock.notify(); 9.   consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2.   lock.wait(); 5.   lock.notify(); 9.   consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2.   lock.wait(); 5.   lock.notify(); 9.   consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2.   lock.wait(); 5.   lock.notify(); 9.   consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
Wait/Notify: Details Often the lock object is the resource itself Sometimes the lock object is the producer thread itself
Wait/Notify Example: Blocking Queue class BlockingQueue extends Queue {   public synchronized Object remove() {     while (isEmpty()) {       wait();     // really this.wait()     }     return super.remove();   }   public synchronized void add(Object o) {     super.add(o);     notifyAll();  // this.notifyAll()   } }
The End 	….. Thank You …..

Contenu connexe

Tendances

Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency begining
maksym220889
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
vamsi krishna
 
ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)
Makoto Yamazaki
 
ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)
Makoto Yamazaki
 

Tendances (20)

Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java synchronizers
Java synchronizersJava synchronizers
Java synchronizers
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
04 threads
04 threads04 threads
04 threads
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency begining
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
 
Jnp
JnpJnp
Jnp
 
Understanding Monitor in Dalvik
Understanding Monitor in DalvikUnderstanding Monitor in Dalvik
Understanding Monitor in Dalvik
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with netty
 
Deep dive into OSGi Lifecycle Layer
Deep dive into OSGi Lifecycle LayerDeep dive into OSGi Lifecycle Layer
Deep dive into OSGi Lifecycle Layer
 
OSGi Training for Carbon Developers
OSGi Training for Carbon DevelopersOSGi Training for Carbon Developers
OSGi Training for Carbon Developers
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor Concurrency
 
ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)
 
ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Thread dumps
Thread dumpsThread dumps
Thread dumps
 

En vedette (7)

Social Media Marketing Research Companies
Social Media Marketing Research CompaniesSocial Media Marketing Research Companies
Social Media Marketing Research Companies
 
Resume bab 11
Resume bab 11Resume bab 11
Resume bab 11
 
Estratificacion(1) dane
Estratificacion(1) daneEstratificacion(1) dane
Estratificacion(1) dane
 
Bluetooth profile
Bluetooth profileBluetooth profile
Bluetooth profile
 
Presentation for colt_303
Presentation for colt_303Presentation for colt_303
Presentation for colt_303
 
Domain investing-moniker
Domain investing-monikerDomain investing-moniker
Domain investing-moniker
 
Operators
OperatorsOperators
Operators
 

Similaire à Threads

07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
nimbalkarvikram966
 

Similaire à Threads (20)

Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptx
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Lec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreadingLec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreading
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Threads in java
Threads in javaThreads in java
Threads in java
 
Lecture10
Lecture10Lecture10
Lecture10
 
Thread 1
Thread 1Thread 1
Thread 1
 
Multi-Threading
Multi-ThreadingMulti-Threading
Multi-Threading
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Advance Java
Advance JavaAdvance Java
Advance Java
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Thread
ThreadThread
Thread
 
Concurrency gotchas
Concurrency gotchasConcurrency gotchas
Concurrency gotchas
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 

Plus de Then Murugeshwari

Plus de Then Murugeshwari (20)

Traffic safety
Traffic safetyTraffic safety
Traffic safety
 
P h indicators
P h indicatorsP h indicators
P h indicators
 
Avogadro's law
Avogadro's lawAvogadro's law
Avogadro's law
 
Resonance
ResonanceResonance
Resonance
 
Microwave remote sensing
Microwave remote sensingMicrowave remote sensing
Microwave remote sensing
 
Newton's law
Newton's lawNewton's law
Newton's law
 
Surface tension
Surface tensionSurface tension
Surface tension
 
Hook's law
Hook's lawHook's law
Hook's law
 
Hook's law
Hook's lawHook's law
Hook's law
 
ERP components
ERP componentsERP components
ERP components
 
Database fundamentals
Database fundamentalsDatabase fundamentals
Database fundamentals
 
Mosfet
MosfetMosfet
Mosfet
 
Hiperlan
HiperlanHiperlan
Hiperlan
 
Router
RouterRouter
Router
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Thread priorities
Thread prioritiesThread priorities
Thread priorities
 
Identifiers
Identifiers Identifiers
Identifiers
 
Virtual ground
Virtual groundVirtual ground
Virtual ground
 
Semiconductor memory
Semiconductor memorySemiconductor memory
Semiconductor memory
 
Karnaugh map
Karnaugh mapKarnaugh map
Karnaugh map
 

Threads

  • 2. Java Threads A thread is not an object A thread is a flow of control A thread is a series of executed statements A thread is a nested sequence of method calls
  • 3. The Thread Object A thread is not an object A Thread is an object void start() Creates a new thread and makes it runnable void run() The new thread begins its life inside this method
  • 4. Thread Creation Diagram Object A Object BThread (extends Thread) Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { // create thread } void run() { doSomething(); }
  • 5. Thread Creation Diagram Object A Object BThread (extends Thread) Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { // create thread } void run() { doSomething(); }
  • 6. Thread Creation Diagram Object A Object BThread (extends Thread) Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { // create thread } void run() { doSomething(); }
  • 7. Thread Creation Diagram Object A Object BThread (extends Thread) Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { // create thread } void run() { doSomething(); }
  • 8. Thread Creation Diagram Object A Object BThread (extends Thread) Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { // create thread } void run() { doSomething(); }
  • 9. Thread Creation Diagram Object A Object BThread (extends Thread) Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { // create thread } void run() { doSomething(); }
  • 10. Thread Creation Diagram Object A Object BThread (extends Thread) Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { // create thread } void run() { doSomething(); }
  • 11. Thread Creation Diagram Object A Object BThread (extends Thread) Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { // create thread } void run() { doSomething(); }
  • 12. Thread Creation Diagram Object A Object BThread (extends Thread) Thread t = new BThread(); t.start(); doMoreStuff(); BThread() { } void start() { // create thread } void run() { doSomething(); }
  • 13. Runnable Interface A helper to the thread object The Thread object’s run() method calls the Runnable object’s run() method Allows threads to run inside any object, regardless of inheritance
  • 14. Runnable Example Talker talker = new Talker(); Thread t = new Thread(talker); t.Start(); --- class Talker implements Runnable { public void run() { while (true) { System.out.println(“yakitty yak”); } } }
  • 15. Thread Lifecycle Active sleep(500) Blocked wake up Born JVM start() suspend() Runnable resume() stop() wait stop() notify Dead block on I/O I/O available
  • 16. Blocking Threads When reading from a stream, if input is not available, the thread will block Thread is suspended (“blocked”) until I/O is available Allows other threads to automatically activate When I/O available, thread wakes back up again Becomes “runnable” Not to be confused with the Runnable interface
  • 17. Thread Scheduling In general, the runnable thread with the highest priority is active (running) Java is priority-preemptive If a high-priority thread wakes up, and a low-priority thread is running Then the high-priority thread gets to run immediately Allows on-demand processing Efficient use of CPU
  • 18. Thread Starvation If a high priority thread never blocks Then all other threads will starve Must be clever about thread priority
  • 19. Thread Priorities: General Strategies Threads that have more to do should get lower priority Counterintuitive Cut to head of line for short tasks Give your I/O-bound threads high priority Wake up, immediately process data, go back to waiting for I/O
  • 20. Thread Synchronization Language keyword: synchronized Takes out a monitor lock on an object Exclusive lock for that thread If lock is currently unavailable, thread will block
  • 21. Thread Synchronization Protects access to code, not to data Make data members private Synchronize accessor methods Puts a “force field” around the locked object so no other threads can enter Actually, it only blocks access to other synchronizing threads
  • 22. Wait and Notify Allows two threads to cooperate Based on a single shared lock object
  • 23. Wait and Notify: Code Consumer: synchronized (lock) { while (!resourceAvailable()) { lock.wait(); } consumeResource(); }
  • 24. Wait and Notify: Code Producer: produceResource(); synchronized (lock) { lock.notifyAll(); }
  • 25. Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2. lock.wait(); 5. lock.notify(); 9. consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
  • 26. Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2. lock.wait(); 5. lock.notify(); 9. consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
  • 27. Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2. lock.wait(); 5. lock.notify(); 9. consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
  • 28. Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2. lock.wait(); 5. lock.notify(); 9. consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
  • 29. Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2. lock.wait(); 5. lock.notify(); 9. consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
  • 30. Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2. lock.wait(); 5. lock.notify(); 9. consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
  • 31. Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2. lock.wait(); 5. lock.notify(); 9. consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
  • 32. Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2. lock.wait(); 5. lock.notify(); 9. consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
  • 33. Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2. lock.wait(); 5. lock.notify(); 9. consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
  • 34. Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2. lock.wait(); 5. lock.notify(); 9. consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
  • 35. Wait/Notify Sequence Lock Object 3. produceResource() 1. synchronized(lock){ 4. synchronized(lock) { 2. lock.wait(); 5. lock.notify(); 9. consumeResource(); 6.} 10. } 7. Reacquire lock 8. Return from wait() Consumer Thread Producer Thread
  • 36. Wait/Notify: Details Often the lock object is the resource itself Sometimes the lock object is the producer thread itself
  • 37. Wait/Notify Example: Blocking Queue class BlockingQueue extends Queue { public synchronized Object remove() { while (isEmpty()) { wait(); // really this.wait() } return super.remove(); } public synchronized void add(Object o) { super.add(o); notifyAll(); // this.notifyAll() } }
  • 38. The End ….. Thank You …..