SCJP Chapter 9

Page 39

CertPrs8/Java 5 Cert. Study Guide/Sierra-Bates/225360-6/Chapter 9

Synchronization and Locks (Exam Objective 4.3)

711

1. Create a class and extend the Thread class.

2. Override the run() method of Thread. This is where the synchronized block of code will go.

3. For our three thread objects to share the same object, we will need to create a constructor that accepts a StringBuffer object in the argument.

4. The synchronized block of code will obtain a lock on the StringBuffer object from step 3.

5. Within the block, output the StringBuffer 100 times and then increment the letter in the StringBuffer. You can check Chapter 5 for StringBuffer methods that will help with this.

6. Finally, in the main() method, create a single StringBuffer object using the letter A, then create three instances of our class and start all three of them.

What Happens If a thread Can't Get the Lock? If a thread tries to enter a synchronized method and the lock is already taken, the thread is said to be blocked on the object's lock. Essentially, the thread goes into a kind of pool for that particular object and has to sit there until the lock is released and the thread can again become runnable/running. Just because a lock is released doesn't mean any particular thread will get it. There might be three threads waiting for a single lock, for example, and there's no guarantee that the thread that has waited the longest will get the lock first. When thinking about blocking, it's important to pay attention to which objects are being used for locking. n Threads calling non-static synchronized methods in the same class will

only block each other if they're invoked using the same instance. That's because they each lock on this instance, and if they're called using two different instances, they get two locks, which do not interfere with each other. n Threads calling static synchronized methods in the same class will always

block each other—they all lock on the same Class instance. n A static synchronized method and a non-static synchronized method

will not block each other, ever. The static method locks on a Class instance while the non-static method locks on the this instance—these actions do not interfere with each other at all.

ch9-1128f.indd 711

11/28/05 12:17:02 PM


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.