This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread Synchronization code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread Synchronization code" Watch "Thread Synchronization code" New topic
Author

Thread Synchronization code

Pallavi Chakraborty
Ranch Hand

Joined: Jan 18, 2003
Posts: 93
Hello everybody,
I tried to write the following code on Thread Synchronization. The aim is to create an array and have two coordinated methods on it, one to add a value and the other to get the added value.
I am getting the output I wanted but that is followed by some errors.

Output:
The value put in is10
The value we are getting is10The value put in is20
The value we are getting is20The value put in is30
The value we are getting is30The value put in is40
The value we are getting is40The value put in is50
The value we are getting is50java.lang.ArrayIndexOutOfBoundsException: 5
at ThreadStuff.putvalue(ThreadStuff.java:6)
at ThreadStuff.run(ThreadStuff.java:18)
I want to know where I am going wrong and how I can incorporate the sleep() into the code.
Thank you all in advance
Pallavi
at java.lang.Thread.run(Thread.java:536)
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
p <= 5 should be p < 5 because of: int OurArray[] = new int[5].
You can use this to sleep for 1000 ms (1 second)

Where to put it? It depends on what effect you want. You could put it at the end of the for loop iteration to slow it down.
Or between the calls to the putValue method and the getValue method to increase the chance that another thread gets to run between the calls.
[ March 23, 2003: Message edited by: Barry Gaunt ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Pallavi Chakraborty
Ranch Hand

Joined: Jan 18, 2003
Posts: 93
Hello Barry,
Thank you. I changed the code:
Here it is:

The Thread name is printed out as Thread-1. What is returned for a getName().I thought it would be t1.
Thank you
Pallavi
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
If you want to give your thread a name other than the generated one you have to specify the name:
Thread t1 = new Thread(ts1, "t1");
Pallavi Chakraborty
Ranch Hand

Joined: Jan 18, 2003
Posts: 93
Thank you ver much, Barry.
Got it now ..
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread Synchronization code