Escolar Documentos
Profissional Documentos
Cultura Documentos
Multithreaded
Programming in Java
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/java5.html
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
5 J2EE training: http://courses.coreservlets.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!
...
...
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();
}
}
...
}
new
I/O completed
ready
notify()
times expires
or interrupted blocked
dispatch
waiting yield()
sleeping
sleep()
Block on I/O
wait() running
run completes
dead
Summary
• Start a thread in its own separate world
– Extend Thread, put the code in run(), instantiate the
subclass of Thread, call start
• Usually done when the operations performed in the run
method are relatively independent of the main application
• Start a thread in an existing object
– Have the main class implement Runnable. Put run() in the
main class. Call new Thread(theRunnable), call start.
• Usually done when the operations performed in the run
method are part of the main application
• Avoid race conditions by updating the
shared resource in a synchronized block
• Other methods to know about
– Thread.currentThread, Thread.sleep
37 J2EE training: http://courses.coreservlets.com
© 2007 Marty Hall
Questions?