SlideShare a Scribd company logo
1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Multithreaded
Programming
Multithreaded Programming2 www.corewebprogramming.com
Agenda
• Why threads?
• Approaches for starting threads
– Separate class approach
– Callback approach
• Solving common thread problems
• Synchronizing access to shared resources
• Thread life cycle
• Stopping threads
Multithreaded Programming3 www.corewebprogramming.com
Concurrent Programming
Using Java Threads
• Motivation
– Efficiency
• Downloading network data files
– Convenience
• A clock icon
– Multi-client applications
• HTTP Server, SMTP Server
• Caution
– Significantly harder to debug and maintain
• Two Main Approaches:
– Make a self-contained subclass of Thread with the
behavior you want
– Implement the Runnable interface and put behavior in
the run method of that object
Multithreaded Programming4 www.corewebprogramming.com
Thread Mechanism One:
Making a Thread Subclass
• Create a separate subclass of Thread
– No import statements needed: Thread is in java.lang
• Put the actions to be performed in the run
method of the subclass
– public void run() { … }
• Create an instance of your Thread subclass
– Or lots of instances if you want lots of threads
• Call that instance’s start method
– You put the code in run, but you call start!
Multithreaded Programming5 www.corewebprogramming.com
Thread Mechanism One:
Making a Thread Subclass
public class DriverClass extends SomeClass {
...
public void startAThread() {
// Create a Thread object
ThreadClass thread = new ThreadClass();
// Start it in a separate process
thread.start();
}
}
public class ThreadClass extends Thread {
public void run() {
// Thread behavior here
}
}
Multithreaded Programming6 www.corewebprogramming.com
Thread Mechanism One:
Example
public class Counter extends Thread {
private static int totalNum = 0;
private int currentNum, loopLimit;
public Counter(int loopLimit) {
this.loopLimit = loopLimit;
currentNum = totalNum++;
}
private void pause(double seconds) {
try { Thread.sleep(Math.round(1000.0*seconds)); }
catch(InterruptedException ie) {}
}
...
Multithreaded Programming7 www.corewebprogramming.com
Thread Mechanism One:
Example (Continued)
...
/** When run finishes, the thread exits. */
public void run() {
for(int i=0; i<loopLimit; i++) {
System.out.println("Counter " + currentNum
+ ": " + i);
pause(Math.random()); // Sleep for up to 1 second
}
}
}
Multithreaded Programming8 www.corewebprogramming.com
Thread Mechanism One:
Example (Continued)
public class CounterTest {
public static void main(String[] args) {
Counter c1 = new Counter(5);
Counter c2 = new Counter(5);
Counter c3 = new Counter(5);
c1.start();
c2.start();
c3.start();
}
}
Multithreaded Programming9 www.corewebprogramming.com
Thread Mechanism One: Result
Counter 0: 0
Counter 1: 0
Counter 2: 0
Counter 1: 1
Counter 2: 1
Counter 1: 2
Counter 0: 1
Counter 0: 2
Counter 1: 3
Counter 2: 2
Counter 0: 3
Counter 1: 4
Counter 0: 4
Counter 2: 3
Counter 2: 4
Multithreaded Programming10 www.corewebprogramming.com
Thread Mechanism Two:
Implementing Runnable
• Put the actions to be performed in the run
method of your existing class
• Have class implement Runnable interface
– If your class already extends some other class (e.g.,
Applet), why can't it still extend Thread? Because Java
does not support multiple inheritance.
• Construct an instance of Thread passing in
the existing object (i.e., the Runnable)
– Thread t = new Thread(theRunnableObject);
• Call that Thread’s start method
– t.start();
Multithreaded Programming11 www.corewebprogramming.com
Thread Mechanism Two:
Implementing Runnable (Cont.)
public class ThreadedClass extends AnyClass
implements Runnable {
public void run() {
// Thread behavior here
// If you want to access thread instance
// (e.g. to get private per-thread data), use
// Thread.currentThread().
}
public void startThread() {
Thread t = new Thread(this);
t.start(); // Calls back to run method in this
}
...
}
Multithreaded Programming12 www.corewebprogramming.com
Thread Mechanism Two:
Example
public class Counter2 implements Runnable {
private static int totalNum = 0;
private int currentNum, loopLimit;
public Counter2(int loopLimit) {
this.loopLimit = loopLimit;
currentNum = totalNum++;
Thread t = new Thread(this);
t.start();
}
...
Multithreaded Programming13 www.corewebprogramming.com
Thread Mechanism Two:
Example (Continued)
...
private void pause(double seconds) {
try { Thread.sleep(Math.round(1000.0*seconds)); }
catch(InterruptedException ie) {}
}
public void run() {
for(int i=0; i<loopLimit; i++) {
System.out.println("Counter " + currentNum
+ ": " + i);
pause(Math.random()); // Sleep for up to 1 second
}
}
}
Multithreaded Programming14 www.corewebprogramming.com
Thread Mechanism Two:
Example (Continued)
public class Counter2Test {
public static void main(String[] args) {
Counter2 c1 = new Counter2(5);
Counter2 c2 = new Counter2(5);
Counter2 c3 = new Counter2(5);
}
}
Multithreaded Programming15 www.corewebprogramming.com
Thread Mechanism Two: Result
Counter 0: 0
Counter 1: 0
Counter 2: 0
Counter 1: 1
Counter 1: 2
Counter 0: 1
Counter 1: 3
Counter 2: 1
Counter 0: 2
Counter 0: 3
Counter 1: 4
Counter 2: 2
Counter 2: 3
Counter 0: 4
Counter 2: 4
Multithreaded Programming16 www.corewebprogramming.com
Race Conditions: Example
public class BuggyCounterApplet extends Applet
implements Runnable{
private int totalNum = 0;
private int loopLimit = 5;
public void start() {
Thread t;
for(int i=0; i<3; i++) {
t = new Thread(this);
t.start();
}
}
private void pause(double seconds) {
try { Thread.sleep(Math.round(1000.0*seconds)); }
catch(InterruptedException ie) {}
}
...
Multithreaded Programming17 www.corewebprogramming.com
Race Conditions: Example
(Continued)
...
public void run() {
int currentNum = totalNum;
System.out.println("Setting currentNum to "
+ currentNum);
totalNum = totalNum + 1;
for(int i=0; i<loopLimit; i++) {
System.out.println("Counter "
+ currentNum + ": " + i);
pause(Math.random());
}
}
}
• What's wrong with this code?
Multithreaded Programming18 www.corewebprogramming.com
Race Conditions: Result
• Occasional Output
Setting currentNum to 0
Counter 0: 0
Setting currentNum to 1
Setting currentNum to 1
Counter 0: 1
Counter 1: 0
Counter 1: 0
Counter 0: 2
Counter 0: 3
Counter 1: 1
Counter 0: 4
Counter 1: 1
Counter 1: 2
Counter 1: 3
Counter 1: 2
Counter 1: 3
Counter 1: 4
Counter 1: 4
• Usual Output
Setting currentNum to 0
Counter 0: 0
Setting currentNum to 1
Counter 1: 0
Setting currentNum to 2
Counter 2: 0
Counter 2: 1
Counter 1: 1
Counter 0: 1
Counter 2: 2
Counter 0: 2
Counter 1: 2
Counter 1: 3
Counter 0: 3
Counter 2: 3
Counter 1: 4
Counter 2: 4
Counter 0: 4
Multithreaded Programming19 www.corewebprogramming.com
Race Conditions: Solution?
• Do things in a single step
public void run() {
int currentNum = totalNum++;
System.out.println("Setting currentNum to "
+ currentNum);
for(int i=0; i<loopLimit; i++) {
System.out.println("Counter "
+ currentNum + ": " + i);
pause(Math.random());
}
}
Multithreaded Programming20 www.corewebprogramming.com
Arbitrating Contention for
Shared Resources
• Synchronizing a Section of Code
synchronized(someObject) {
code
}
• Normal interpretation
– Once a thread enters the code, no other thread can enter
until the first thread exits.
• Stronger interpretation
– Once a thread enters the code, no other thread can enter
any section of code that is synchronized using the same
“lock” tag
Multithreaded Programming21 www.corewebprogramming.com
Arbitrating Contention for
Shared Resources
• Synchronizing an Entire Method
public synchronized void someMethod() {
body
}
• Note that this is equivalent to
public void someMethod() {
synchronized(this) {
body
}
}
Multithreaded Programming22 www.corewebprogramming.com
Common Synchronization Bug
• What’s wrong with this class?
public class SomeThreadedClass extends Thread {
private static RandomClass someSharedObject;
...
public synchronized void doSomeOperation() {
accessSomeSharedObject();
}
...
public void run() {
while(someCondition) {
doSomeOperation(); // Accesses shared data
doSomeOtherOperation();// No shared data
}
}
}
Multithreaded Programming23 www.corewebprogramming.com
Synchronization Solution
• Solution 1: synchronize on the shared data
public void doSomeOperation() {
synchronized(someSharedObject) {
accessSomeSharedObject();
}
}
• Solution 2: synchronize on the class object
public void doSomeOperation() {
synchronized(SomeThreadedClass.class) {
accessSomeSharedObject();
}
}
– Note that if you synchronize a static method, the lock is the
corresponding Class object, not this
Multithreaded Programming24 www.corewebprogramming.com
Synchronization Solution
(Continued)
• Solution 3: synchronize on arbitrary object
public class SomeThreadedClass extends Thread {
private static Object lockObject
= new Object();
...
public void doSomeOperation() {
synchronized(lockObject) {
accessSomeSharedObject();
}
}
...
}
– Why doesn't this problem usually occur with Runnable?
Multithreaded Programming25 www.corewebprogramming.com
Thread Lifecycle
new
wait()
yield()
notify()
dispatch
ready
start()
running
waiting
blocked
sleeping
sleep()
Block on I/O
times expires
or interrupted
I/O completed
deadrun completes
Multithreaded Programming26 www.corewebprogramming.com
Useful Thread Constructors
• Thread()
– Default version you get when you call constructor of your
custom Thread subclass.
• Thread(Runnable target)
– Creates a thread, that, once started, will execute the run
method of the target
• Thread(ThreadGroup group,
Runnable target)
– Creates a thread and places it in the specified thread group
– A ThreadGroup is a collection of threads that can be
operated on as a set
• Thread(String name)
– Creates a thread with the given name
– Useful for debugging
Multithreaded Programming27 www.corewebprogramming.com
Thread Priorities
• A thread’s default priority is the same as the
creating thread
• Thread API defines three thread priorities
•Thread.MAX_PRIORITY (typically 10)
•Thread.NORM_PRIORITY (typically 5)
•Thread.MIN_PRIORITY (typically 1)
• Problems
– A Java thread priority may map differently to the thread
priorities of the underlying OS
• Solaris has 232–1 priority level; Windows NT has 7
user priority levels
– Starvation can occur for lower-priority threads if the
higher-priority threads never terminate, sleep, or wait for
I/O
Multithreaded Programming28 www.corewebprogramming.com
Useful Thread Methods
• currentThread
– Returns a reference to the currently executing thread
– This is a static method that can be called by arbitrary methods,
not just from within a Thread object
• I.e., anyone can call Thread.currentThread
• interrupt
– One of two outcomes:
• If the thread is executing join, sleep, or wait, an
InterruptedException is thrown
• Sets a flag, from which the interrupted thread can check
(isInterrupted)
• interrupted
– Checks whether the currently executing thread has a request for
interruption (checks flag) and clears the flag
Multithreaded Programming29 www.corewebprogramming.com
Useful Thread Methods
(Continued)
• isInterrupted
– Simply checks whether the thread’s interrupt flag has
been set (does not modify the flag)
• Reset the flag by calling interrupted from within
the run method of the flagged thread
• join
– Joins to another thread by simply waiting (sleeps) until
the other thread has completed execution
• isDaemon/setDaemon
– Determines or set the thread to be a daemon
– A Java program will exit when the only active threads
remaining are daemon threads
Multithreaded Programming30 www.corewebprogramming.com
Useful Thread Methods
(Continued)
• start
– Initializes the thread and then calls run
– If the thread was constructed by providing a Runnable,
then start calls the run method of that Runnable
• run
– The method in which a created thread will execute
– Do not call run directly; call start on the thread object
– When run completes the thread enters a dead state and
cannot be restarted
Multithreaded Programming31 www.corewebprogramming.com
Useful Thread Methods
(Continued)
• sleep
– Causes the currently executing thread to do a
nonbusy wait for at least the amount of time
(milliseconds), unless interrupted
– As a static method, may be called for nonthreaded
applications as well
• I.e., anyone can call Thread.sleep
• Note that sleep throws InterruptedException. Need
try/catch
• yield
– Allows any other threads of the same or higher
priority to execute (moves itself to the end of the
priority queue)
– If all waiting threads have a lower priority, then the
yielding thread remains on the CPU
Multithreaded Programming32 www.corewebprogramming.com
Useful Thread Methods
(Continued)
• wait/waitForAll
– Releases the lock for other threads and suspends itself
(placed in a wait queue associated with the lock)
– Thread can be restarted through notify or notifyAll
– These methods must be synchronized on the lock object of
importance
• notify/notifyAll
– Wakes up all threads waiting for the lock
– A notified doesn’t begin immediate execution, but is placed in
the runnable thread queue
Multithreaded Programming33 www.corewebprogramming.com
Stopping a Thread
public class ThreadExample implements Runnable {
private boolean running;
public ThreadExample()
Thread thread = new Thread(this);
thread.start();
}
public void run(){
running = true;
while (running) {
...
}
doCleanup();
}
public void setRunning(boolean running) {
this.running = running;
}
}
Multithreaded Programming34 www.corewebprogramming.com
Signaling with wait and notify
public class ConnectionPool implements Runnable {
...
public synchronized Connection getConnection() {
if (availableConnections.isEmpty()) {
try {
wait();
} catch(InterruptedException ie) {}
// Someone freed up a connection, so try again.
return(getConnection());
} else {
// Get available connection
...
return(connection)
}
}
Multithreaded Programming35 www.corewebprogramming.com
Signaling with wait and notify
(Continued)
public synchronized void free(Connection connection) {
busyConnections.removeElement(connection);
availableConnections.addElement(connection);
// Wake up threads that are waiting
// for a connection
notifyAll();
}
...
}
Multithreaded Programming36 www.corewebprogramming.com
Summary
• Achieve multithreaded behavior by
– Inheriting directly from Thread
(separate class approach)
– Implementing the Runnable interface
(callback approach)
• In either case, put your code in the run
method. Call start on the Thread object.
• Avoid race conditions by placing the shared
resource in a synchronized block
• You can’t restart a dead thread
• Stop threads by setting a flag that the
thread's run method checks
37 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Questions?

More Related Content

What's hot

Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Sachintha Gunasena
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Java concurrency
Java concurrencyJava concurrency
Java concurrencyducquoc_vn
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37myrajendra
 
Non-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itNon-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itAlexey Fyodorov
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfacekeval_thummar
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 

What's hot (20)

Java adv
Java advJava adv
Java adv
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Thread 1
Thread 1Thread 1
Thread 1
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
java threads
java threadsjava threads
java threads
 
Threads
ThreadsThreads
Threads
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
Non-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itNon-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need it
 
04 threads
04 threads04 threads
04 threads
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interface
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 

Viewers also liked

6. Внутренние источники кандидатов и концепция сотрудников-бумерангов 03
6. Внутренние источники кандидатов и концепция сотрудников-бумерангов 036. Внутренние источники кандидатов и концепция сотрудников-бумерангов 03
6. Внутренние источники кандидатов и концепция сотрудников-бумерангов 03Katie Danilova
 
Shall I run away?
Shall I run away?Shall I run away?
Shall I run away?Gabor Szabo
 
Herramientas de diseño de pagina
Herramientas de diseño de paginaHerramientas de diseño de pagina
Herramientas de diseño de paginakarlaosakiugmex
 
Minimális Piaci Lefedettség és a többi
Minimális Piaci Lefedettség és a többiMinimális Piaci Lefedettség és a többi
Minimális Piaci Lefedettség és a többiSoftinvent
 
Servizi e Best Practice hotel-LAB.com
Servizi e Best Practice hotel-LAB.comServizi e Best Practice hotel-LAB.com
Servizi e Best Practice hotel-LAB.comGiulia Zanin
 
Brasil aumenta lotação dos abrigos de velhos carentes de caridade
Brasil aumenta lotação dos abrigos de velhos carentes de caridadeBrasil aumenta lotação dos abrigos de velhos carentes de caridade
Brasil aumenta lotação dos abrigos de velhos carentes de caridadeRoberto Rabat Chame
 
Perfeito em cima,péssimo em ...
Perfeito em cima,péssimo em ...Perfeito em cima,péssimo em ...
Perfeito em cima,péssimo em ...Roberto Rabat Chame
 
PTH Solutions Inc. Company Synopsis 2011
PTH Solutions Inc.  Company Synopsis 2011PTH Solutions Inc.  Company Synopsis 2011
PTH Solutions Inc. Company Synopsis 2011Peter Pham
 
Investigacion sobre la robotica
Investigacion sobre la roboticaInvestigacion sobre la robotica
Investigacion sobre la roboticaAidee Viveros
 
Global Book Tour Packages
Global Book Tour PackagesGlobal Book Tour Packages
Global Book Tour PackagesVal Slastnikov
 
Intro To Film Loop
Intro To Film LoopIntro To Film Loop
Intro To Film LoopRachel Jones
 
14multithreaded Graphics
14multithreaded Graphics14multithreaded Graphics
14multithreaded GraphicsAdil Jafri
 

Viewers also liked (20)

Leverage Report
Leverage ReportLeverage Report
Leverage Report
 
Happy New Year 2014
Happy New Year 2014Happy New Year 2014
Happy New Year 2014
 
Acertijo 26
Acertijo 26Acertijo 26
Acertijo 26
 
Owl Clock
Owl ClockOwl Clock
Owl Clock
 
6. Внутренние источники кандидатов и концепция сотрудников-бумерангов 03
6. Внутренние источники кандидатов и концепция сотрудников-бумерангов 036. Внутренние источники кандидатов и концепция сотрудников-бумерангов 03
6. Внутренние источники кандидатов и концепция сотрудников-бумерангов 03
 
Shall I run away?
Shall I run away?Shall I run away?
Shall I run away?
 
Herramientas de diseño de pagina
Herramientas de diseño de paginaHerramientas de diseño de pagina
Herramientas de diseño de pagina
 
Minimális Piaci Lefedettség és a többi
Minimális Piaci Lefedettség és a többiMinimális Piaci Lefedettség és a többi
Minimális Piaci Lefedettség és a többi
 
Servizi e Best Practice hotel-LAB.com
Servizi e Best Practice hotel-LAB.comServizi e Best Practice hotel-LAB.com
Servizi e Best Practice hotel-LAB.com
 
Brasil aumenta lotação dos abrigos de velhos carentes de caridade
Brasil aumenta lotação dos abrigos de velhos carentes de caridadeBrasil aumenta lotação dos abrigos de velhos carentes de caridade
Brasil aumenta lotação dos abrigos de velhos carentes de caridade
 
Pharma report 2013
Pharma report 2013Pharma report 2013
Pharma report 2013
 
Perfeito em cima,péssimo em ...
Perfeito em cima,péssimo em ...Perfeito em cima,péssimo em ...
Perfeito em cima,péssimo em ...
 
26xslt
26xslt26xslt
26xslt
 
PTH Solutions Inc. Company Synopsis 2011
PTH Solutions Inc.  Company Synopsis 2011PTH Solutions Inc.  Company Synopsis 2011
PTH Solutions Inc. Company Synopsis 2011
 
Investigacion sobre la robotica
Investigacion sobre la roboticaInvestigacion sobre la robotica
Investigacion sobre la robotica
 
Global Book Tour Packages
Global Book Tour PackagesGlobal Book Tour Packages
Global Book Tour Packages
 
Intro To Film Loop
Intro To Film LoopIntro To Film Loop
Intro To Film Loop
 
453 an 13_novembro_2013.ok
453 an 13_novembro_2013.ok453 an 13_novembro_2013.ok
453 an 13_novembro_2013.ok
 
411 an 26_dezembro_2012.ok
411 an 26_dezembro_2012.ok411 an 26_dezembro_2012.ok
411 an 26_dezembro_2012.ok
 
14multithreaded Graphics
14multithreaded Graphics14multithreaded Graphics
14multithreaded Graphics
 

Similar to 13multithreaded Programming

Core Java Programming Language (JSE) : Chapter XII - Threads
Core Java Programming Language (JSE) : Chapter XII -  ThreadsCore Java Programming Language (JSE) : Chapter XII -  Threads
Core Java Programming Language (JSE) : Chapter XII - ThreadsWebStackAcademy
 
06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VIHari Christian
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join frameworkMinh Tran
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
MULTITHREADING CONCEPT
MULTITHREADING CONCEPTMULTITHREADING CONCEPT
MULTITHREADING CONCEPTRAVI MAURYA
 
JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdfMohit Kumar
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threadsYnon Perek
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoinknight1128
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming LanguagesYudong Li
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreadingssusere538f7
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 

Similar to 13multithreaded Programming (20)

Operating System lab
Operating System labOperating System lab
Operating System lab
 
Multi Threading
Multi ThreadingMulti Threading
Multi Threading
 
Core Java Programming Language (JSE) : Chapter XII - Threads
Core Java Programming Language (JSE) : Chapter XII -  ThreadsCore Java Programming Language (JSE) : Chapter XII -  Threads
Core Java Programming Language (JSE) : Chapter XII - Threads
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VI
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
MULTITHREADING CONCEPT
MULTITHREADING CONCEPTMULTITHREADING CONCEPT
MULTITHREADING CONCEPT
 
JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdf
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
Thread
ThreadThread
Thread
 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming Languages
 
Threads
ThreadsThreads
Threads
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 

More from Adil Jafri

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5Adil Jafri
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net BibleAdil Jafri
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming ClientsAdil Jafri
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran TochAdil Jafri
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10Adil Jafri
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx TutorialsAdil Jafri
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbAdil Jafri
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12Adil Jafri
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash TutorialAdil Jafri
 

More from Adil Jafri (20)

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5
 
Php How To
Php How ToPhp How To
Php How To
 
Php How To
Php How ToPhp How To
Php How To
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net Bible
 
Tcpip Intro
Tcpip IntroTcpip Intro
Tcpip Intro
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
 
Jsp Tutorial
Jsp TutorialJsp Tutorial
Jsp Tutorial
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10
 
Javascript
JavascriptJavascript
Javascript
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx Tutorials
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand Ejb
 
Html Css
Html CssHtml Css
Html Css
 
Digwc
DigwcDigwc
Digwc
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12
 
Html Frames
Html FramesHtml Frames
Html Frames
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash Tutorial
 
C Programming
C ProgrammingC Programming
C Programming
 

Recently uploaded

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Product School
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxAbida Shariff
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsExpeed Software
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1DianaGray10
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backElena Simperl
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutesconfluent
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...Sri Ambati
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...Product School
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Product School
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaRTTS
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...Product School
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsPaul Groth
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
 

Recently uploaded (20)

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 

13multithreaded Programming

  • 1. 1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Multithreaded Programming
  • 2. Multithreaded Programming2 www.corewebprogramming.com Agenda • Why threads? • Approaches for starting threads – Separate class approach – Callback approach • Solving common thread problems • Synchronizing access to shared resources • Thread life cycle • Stopping threads
  • 3. Multithreaded Programming3 www.corewebprogramming.com Concurrent Programming Using Java Threads • Motivation – Efficiency • Downloading network data files – Convenience • A clock icon – Multi-client applications • HTTP Server, SMTP Server • Caution – Significantly harder to debug and maintain • Two Main Approaches: – Make a self-contained subclass of Thread with the behavior you want – Implement the Runnable interface and put behavior in the run method of that object
  • 4. Multithreaded Programming4 www.corewebprogramming.com Thread Mechanism One: Making a Thread Subclass • Create a separate subclass of Thread – No import statements needed: Thread is in java.lang • Put the actions to be performed in the run method of the subclass – public void run() { … } • Create an instance of your Thread subclass – Or lots of instances if you want lots of threads • Call that instance’s start method – You put the code in run, but you call start!
  • 5. Multithreaded Programming5 www.corewebprogramming.com Thread Mechanism One: Making a Thread Subclass public class DriverClass extends SomeClass { ... public void startAThread() { // Create a Thread object ThreadClass thread = new ThreadClass(); // Start it in a separate process thread.start(); } } public class ThreadClass extends Thread { public void run() { // Thread behavior here } }
  • 6. Multithreaded Programming6 www.corewebprogramming.com Thread Mechanism One: Example public class Counter extends Thread { private static int totalNum = 0; private int currentNum, loopLimit; public Counter(int loopLimit) { this.loopLimit = loopLimit; currentNum = totalNum++; } private void pause(double seconds) { try { Thread.sleep(Math.round(1000.0*seconds)); } catch(InterruptedException ie) {} } ...
  • 7. Multithreaded Programming7 www.corewebprogramming.com Thread Mechanism One: Example (Continued) ... /** When run finishes, the thread exits. */ public void run() { for(int i=0; i<loopLimit; i++) { System.out.println("Counter " + currentNum + ": " + i); pause(Math.random()); // Sleep for up to 1 second } } }
  • 8. Multithreaded Programming8 www.corewebprogramming.com Thread Mechanism One: Example (Continued) public class CounterTest { public static void main(String[] args) { Counter c1 = new Counter(5); Counter c2 = new Counter(5); Counter c3 = new Counter(5); c1.start(); c2.start(); c3.start(); } }
  • 9. Multithreaded Programming9 www.corewebprogramming.com Thread Mechanism One: Result Counter 0: 0 Counter 1: 0 Counter 2: 0 Counter 1: 1 Counter 2: 1 Counter 1: 2 Counter 0: 1 Counter 0: 2 Counter 1: 3 Counter 2: 2 Counter 0: 3 Counter 1: 4 Counter 0: 4 Counter 2: 3 Counter 2: 4
  • 10. Multithreaded Programming10 www.corewebprogramming.com Thread Mechanism Two: Implementing Runnable • Put the actions to be performed in the run method of your existing class • Have class implement Runnable interface – If your class already extends some other class (e.g., Applet), why can't it still extend Thread? Because Java does not support multiple inheritance. • Construct an instance of Thread passing in the existing object (i.e., the Runnable) – Thread t = new Thread(theRunnableObject); • Call that Thread’s start method – t.start();
  • 11. Multithreaded Programming11 www.corewebprogramming.com Thread Mechanism Two: Implementing Runnable (Cont.) public class ThreadedClass extends AnyClass implements Runnable { public void run() { // Thread behavior here // If you want to access thread instance // (e.g. to get private per-thread data), use // Thread.currentThread(). } public void startThread() { Thread t = new Thread(this); t.start(); // Calls back to run method in this } ... }
  • 12. Multithreaded Programming12 www.corewebprogramming.com Thread Mechanism Two: Example public class Counter2 implements Runnable { private static int totalNum = 0; private int currentNum, loopLimit; public Counter2(int loopLimit) { this.loopLimit = loopLimit; currentNum = totalNum++; Thread t = new Thread(this); t.start(); } ...
  • 13. Multithreaded Programming13 www.corewebprogramming.com Thread Mechanism Two: Example (Continued) ... private void pause(double seconds) { try { Thread.sleep(Math.round(1000.0*seconds)); } catch(InterruptedException ie) {} } public void run() { for(int i=0; i<loopLimit; i++) { System.out.println("Counter " + currentNum + ": " + i); pause(Math.random()); // Sleep for up to 1 second } } }
  • 14. Multithreaded Programming14 www.corewebprogramming.com Thread Mechanism Two: Example (Continued) public class Counter2Test { public static void main(String[] args) { Counter2 c1 = new Counter2(5); Counter2 c2 = new Counter2(5); Counter2 c3 = new Counter2(5); } }
  • 15. Multithreaded Programming15 www.corewebprogramming.com Thread Mechanism Two: Result Counter 0: 0 Counter 1: 0 Counter 2: 0 Counter 1: 1 Counter 1: 2 Counter 0: 1 Counter 1: 3 Counter 2: 1 Counter 0: 2 Counter 0: 3 Counter 1: 4 Counter 2: 2 Counter 2: 3 Counter 0: 4 Counter 2: 4
  • 16. Multithreaded Programming16 www.corewebprogramming.com Race Conditions: Example public class BuggyCounterApplet extends Applet implements Runnable{ private int totalNum = 0; private int loopLimit = 5; public void start() { Thread t; for(int i=0; i<3; i++) { t = new Thread(this); t.start(); } } private void pause(double seconds) { try { Thread.sleep(Math.round(1000.0*seconds)); } catch(InterruptedException ie) {} } ...
  • 17. Multithreaded Programming17 www.corewebprogramming.com Race Conditions: Example (Continued) ... public void run() { int currentNum = totalNum; System.out.println("Setting currentNum to " + currentNum); totalNum = totalNum + 1; for(int i=0; i<loopLimit; i++) { System.out.println("Counter " + currentNum + ": " + i); pause(Math.random()); } } } • What's wrong with this code?
  • 18. Multithreaded Programming18 www.corewebprogramming.com Race Conditions: Result • Occasional Output Setting currentNum to 0 Counter 0: 0 Setting currentNum to 1 Setting currentNum to 1 Counter 0: 1 Counter 1: 0 Counter 1: 0 Counter 0: 2 Counter 0: 3 Counter 1: 1 Counter 0: 4 Counter 1: 1 Counter 1: 2 Counter 1: 3 Counter 1: 2 Counter 1: 3 Counter 1: 4 Counter 1: 4 • Usual Output Setting currentNum to 0 Counter 0: 0 Setting currentNum to 1 Counter 1: 0 Setting currentNum to 2 Counter 2: 0 Counter 2: 1 Counter 1: 1 Counter 0: 1 Counter 2: 2 Counter 0: 2 Counter 1: 2 Counter 1: 3 Counter 0: 3 Counter 2: 3 Counter 1: 4 Counter 2: 4 Counter 0: 4
  • 19. Multithreaded Programming19 www.corewebprogramming.com Race Conditions: Solution? • Do things in a single step public void run() { int currentNum = totalNum++; System.out.println("Setting currentNum to " + currentNum); for(int i=0; i<loopLimit; i++) { System.out.println("Counter " + currentNum + ": " + i); pause(Math.random()); } }
  • 20. Multithreaded Programming20 www.corewebprogramming.com Arbitrating Contention for Shared Resources • Synchronizing a Section of Code synchronized(someObject) { code } • Normal interpretation – Once a thread enters the code, no other thread can enter until the first thread exits. • Stronger interpretation – Once a thread enters the code, no other thread can enter any section of code that is synchronized using the same “lock” tag
  • 21. Multithreaded Programming21 www.corewebprogramming.com Arbitrating Contention for Shared Resources • Synchronizing an Entire Method public synchronized void someMethod() { body } • Note that this is equivalent to public void someMethod() { synchronized(this) { body } }
  • 22. Multithreaded Programming22 www.corewebprogramming.com Common Synchronization Bug • What’s wrong with this class? public class SomeThreadedClass extends Thread { private static RandomClass someSharedObject; ... public synchronized void doSomeOperation() { accessSomeSharedObject(); } ... public void run() { while(someCondition) { doSomeOperation(); // Accesses shared data doSomeOtherOperation();// No shared data } } }
  • 23. Multithreaded Programming23 www.corewebprogramming.com Synchronization Solution • Solution 1: synchronize on the shared data public void doSomeOperation() { synchronized(someSharedObject) { accessSomeSharedObject(); } } • Solution 2: synchronize on the class object public void doSomeOperation() { synchronized(SomeThreadedClass.class) { accessSomeSharedObject(); } } – Note that if you synchronize a static method, the lock is the corresponding Class object, not this
  • 24. Multithreaded Programming24 www.corewebprogramming.com Synchronization Solution (Continued) • Solution 3: synchronize on arbitrary object public class SomeThreadedClass extends Thread { private static Object lockObject = new Object(); ... public void doSomeOperation() { synchronized(lockObject) { accessSomeSharedObject(); } } ... } – Why doesn't this problem usually occur with Runnable?
  • 25. Multithreaded Programming25 www.corewebprogramming.com Thread Lifecycle new wait() yield() notify() dispatch ready start() running waiting blocked sleeping sleep() Block on I/O times expires or interrupted I/O completed deadrun completes
  • 26. Multithreaded Programming26 www.corewebprogramming.com Useful Thread Constructors • Thread() – Default version you get when you call constructor of your custom Thread subclass. • Thread(Runnable target) – Creates a thread, that, once started, will execute the run method of the target • Thread(ThreadGroup group, Runnable target) – Creates a thread and places it in the specified thread group – A ThreadGroup is a collection of threads that can be operated on as a set • Thread(String name) – Creates a thread with the given name – Useful for debugging
  • 27. Multithreaded Programming27 www.corewebprogramming.com Thread Priorities • A thread’s default priority is the same as the creating thread • Thread API defines three thread priorities •Thread.MAX_PRIORITY (typically 10) •Thread.NORM_PRIORITY (typically 5) •Thread.MIN_PRIORITY (typically 1) • Problems – A Java thread priority may map differently to the thread priorities of the underlying OS • Solaris has 232–1 priority level; Windows NT has 7 user priority levels – Starvation can occur for lower-priority threads if the higher-priority threads never terminate, sleep, or wait for I/O
  • 28. Multithreaded Programming28 www.corewebprogramming.com Useful Thread Methods • currentThread – Returns a reference to the currently executing thread – This is a static method that can be called by arbitrary methods, not just from within a Thread object • I.e., anyone can call Thread.currentThread • interrupt – One of two outcomes: • If the thread is executing join, sleep, or wait, an InterruptedException is thrown • Sets a flag, from which the interrupted thread can check (isInterrupted) • interrupted – Checks whether the currently executing thread has a request for interruption (checks flag) and clears the flag
  • 29. Multithreaded Programming29 www.corewebprogramming.com Useful Thread Methods (Continued) • isInterrupted – Simply checks whether the thread’s interrupt flag has been set (does not modify the flag) • Reset the flag by calling interrupted from within the run method of the flagged thread • join – Joins to another thread by simply waiting (sleeps) until the other thread has completed execution • isDaemon/setDaemon – Determines or set the thread to be a daemon – A Java program will exit when the only active threads remaining are daemon threads
  • 30. Multithreaded Programming30 www.corewebprogramming.com Useful Thread Methods (Continued) • start – Initializes the thread and then calls run – If the thread was constructed by providing a Runnable, then start calls the run method of that Runnable • run – The method in which a created thread will execute – Do not call run directly; call start on the thread object – When run completes the thread enters a dead state and cannot be restarted
  • 31. Multithreaded Programming31 www.corewebprogramming.com Useful Thread Methods (Continued) • sleep – Causes the currently executing thread to do a nonbusy wait for at least the amount of time (milliseconds), unless interrupted – As a static method, may be called for nonthreaded applications as well • I.e., anyone can call Thread.sleep • Note that sleep throws InterruptedException. Need try/catch • yield – Allows any other threads of the same or higher priority to execute (moves itself to the end of the priority queue) – If all waiting threads have a lower priority, then the yielding thread remains on the CPU
  • 32. Multithreaded Programming32 www.corewebprogramming.com Useful Thread Methods (Continued) • wait/waitForAll – Releases the lock for other threads and suspends itself (placed in a wait queue associated with the lock) – Thread can be restarted through notify or notifyAll – These methods must be synchronized on the lock object of importance • notify/notifyAll – Wakes up all threads waiting for the lock – A notified doesn’t begin immediate execution, but is placed in the runnable thread queue
  • 33. Multithreaded Programming33 www.corewebprogramming.com Stopping a Thread public class ThreadExample implements Runnable { private boolean running; public ThreadExample() Thread thread = new Thread(this); thread.start(); } public void run(){ running = true; while (running) { ... } doCleanup(); } public void setRunning(boolean running) { this.running = running; } }
  • 34. Multithreaded Programming34 www.corewebprogramming.com Signaling with wait and notify public class ConnectionPool implements Runnable { ... public synchronized Connection getConnection() { if (availableConnections.isEmpty()) { try { wait(); } catch(InterruptedException ie) {} // Someone freed up a connection, so try again. return(getConnection()); } else { // Get available connection ... return(connection) } }
  • 35. Multithreaded Programming35 www.corewebprogramming.com Signaling with wait and notify (Continued) public synchronized void free(Connection connection) { busyConnections.removeElement(connection); availableConnections.addElement(connection); // Wake up threads that are waiting // for a connection notifyAll(); } ... }
  • 36. Multithreaded Programming36 www.corewebprogramming.com Summary • Achieve multithreaded behavior by – Inheriting directly from Thread (separate class approach) – Implementing the Runnable interface (callback approach) • In either case, put your code in the run method. Call start on the Thread object. • Avoid race conditions by placing the shared resource in a synchronized block • You can’t restart a dead thread • Stop threads by setting a flag that the thread's run method checks
  • 37. 37 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Questions?