This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
"The real payoff of concurrent execution arises notfrom the fact that applications can be speeded up by artificially introducing concurrency, but from the fact that the real world functions by the execution of concurrent activities.”
• Concurrent execution (on multiprocessing hardware) can improve program performance.
• Many applications are modeled more naturally as systems of concurrently executing threads. A concurrent program preserves the structure of a concurrent problem.
• Concurrent programming facilities enhance the programmer’s ability to “invent” concurrent solutions.
Creating a Thread by Implementingthe Runnable Interface
1. Create a class that implements the Runnable interface, and place the code for the thread in the run() method. public class SimpleRunnable extends SomeClass implements Runnable { public SimpleRunnable() { ... }
public class ThreadTest { public static void main (String[] args) { Runnable r1 = new SimpleRunnable("Hello"); Runnable r2 = new SimpleRunnable("World");
Thread t1 = new Thread(r1); Thread t2 = new Thread(r2);
• A race condition is a set of circumstances in which the relative speeds of two threads can influence the result of program execution. It can occur when two concurrent threads operate on a shared resource in overlapping time intervals.
• Asynchronous communication between two threads can be achieved by defining a third thread as a mailbox.
• Examplepublic class MailBox { public synchronized void write(String message) {…} public synchronized String read() {…} … // other implementation details }
Mailboxes could be created dynamically as needed.
A blocking queue could be used to implement the mailbox.
thread1
thread2
mailbox
Thread Safety(Brian Goetz)
• A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.
• Writing thread-safe code is about managing access to shared, mutable state, where an object’s state is its data.
• Thread-safe classes encapsulate any needed synchronization so that clients need not provide their own.
• Stateless objects and immutable objects are always thread-safe.
• Parameters and local variables (declared within a method) are stored on the run-time stack, and each thread has its on stack. A method that uses only local variables or parameters is always thread safe as long as it doesn’t use parameters to modify mutable objects.
• An object that is accessed by only one thread need not be thread-safe.– simpler, better performance– but … are you sure that it never will be accessed by multiple