Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread Synchronization code

 
Pallavi Chakraborty
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Pallavi Chakraborty
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you ver much, Barry.
Got it now ..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic