File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes KATHY SCJP 1.6 : THREADS, exercise 9-2. Is my code fine? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "KATHY SCJP 1.6 : THREADS, exercise 9-2. Is my code fine?" Watch "KATHY SCJP 1.6 : THREADS, exercise 9-2. Is my code fine?" New topic
Author

KATHY SCJP 1.6 : THREADS, exercise 9-2. Is my code fine?

Rahul Sudip Bose
Ranch Hand

Joined: Jan 21, 2011
Posts: 637

New to threads. I am not sure if my solution is the simplest/correct. It compiles and runs. If there is a better/neater way to do this, please let me know.

Here is the question, page 738 :

In this exercise we will attempt to synchronize a block of code. Within that block of code we will get the lock on an object, so that other threads cannot modify it while the block of code is executing. We will be creating three threads that will all attempt to manipulate the same object. Each thread will output a single letter 100 times, and then increment that letter by one. The object we will be using is StringBuffer. We could synchronize on a String object, but strings cannot be modified once they are created, so we would not be able to increment the letter without generating a new String object. The final output should have 100 As, 100 Bs, and 100 Cs all in unbroken lines.

INSTEAD OF 100, I CHOOSE 5.

Here is my code :


sample outputs :


SCJP 6. Learning more now.
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9307
    
  17

Your code is achieving the desired output but its not correct. You need to synchronize an instance method. Basically you need to get a lock on the object which is being manipulated. How about moving the modifyStringBuff method to Job class (without any parameters) and making it an instance method...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Jatin Dhingra
Greenhorn

Joined: Jun 28, 2010
Posts: 29
Also its good practice to keep Thread and Thread job as two different classes..to be more OO specific. Although it doesnt effect functionality anyhow but just increases readability.
 
jQuery in Action, 2nd edition
 
subject: KATHY SCJP 1.6 : THREADS, exercise 9-2. Is my code fine?