Sunteți pe pagina 1din 3

5/5/13

synchronized lock the object or method (SCJP forum at JavaRanch)

A friendly place for programming greenhorns!

Big Moose Saloon


Search

Java FAQ

Recent Topics

Register / Login

JavaRanch Java Forums Certification Programmer Certification (SCJP/OCPJP)

Author

synchronized lock the object or method


posted 10/15/2001 4:15 PM

R K Singh Ranch Hand Joined: Oct 15, 2001 Posts: 5369

here is the question one of my friend asked me: 1. public class MyThread implements Runnable { 2. private String holdA = "This is "; 3. private int[] holdB = {1,2,3,4,5,6,7,8,9,10}; 4. 5. public static void main(String args[]) { 6. MyThread z = new MyThread(); 7. (new Thread(z)).start(); 8. (new Thread(z)).start(); 9. } 10. 11. public synchronized void run() {
1/3

www.coderanch.com/t/226212/java-programmer-SCJP/certification/synchronized-lock-object-method

5/5/13

synchronized lock the object or method (SCJP forum at JavaRanch)

12. for(int w = 0;w < 10;w++) { 13. System.out.println(holdA + holdB[w] + "."); 14. } 15. } 16. } They say answer is : the program prints each value in the holdB array at the end of the "This is " line. Each value is printed in order from 1 to 10 and, after the value 10 prints, it starts printing the values 1 to 10 in order again. ----------------But I read that lock is on object and you can not execute the same synchronized method of the SAME object... and as here there are two different objects of Thread, how they could be synchronized?? [This message has been edited by ravish kumar (edited October 15, 2001).]

"Thanks to Indian media who has over the period of time swiped out intellectual taste from mass Indian population." C hetan Parekh

William Brogden Author and all-around good cowpoke Rancher Joined: Mar 22, 2000 Posts: 12235

posted 10/16/2001 2:55 AM

There is one MyThread (bad name for demonstration) object with two competing Threads trying to execute the synchronized method in the one object. Therefore one Thread runs to completion before the other gets to start. Bill

Java Resources at www.wbrogden.com

R K Singh Ranch Hand Joined: Oct 15, 2001 Posts: 5369

posted 10/16/2001 11:54 AM

Thanks Bill I got you.

I agree. Here's the link: http://aspose.com/file-tools

www.coderanch.com/t/226212/java-programmer-SCJP/certification/synchronized-lock-object-method

2/3

5/5/13

synchronized lock the object or method (SCJP forum at JavaRanch)

subject: synchronized lock the object or method

Similar Threads Hi Thread doubt Threads Sun sample question. Thread Program Synchronized Thread
All times above are in your local time zone & format.T he current ranch time (not your local time) is May 05, 2013 00:23:57 .

Contact Us | Powered by JForum |

C opyright 1998-2013 Paul W he aton

www.coderanch.com/t/226212/java-programmer-SCJP/certification/synchronized-lock-object-method

3/3

S-ar putea să vă placă și