Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

I need help in a synchronization threads exercise

 
                            
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an exercise about threads synchronization.

I am working in an exercise which adds 1 and Subtract 1 ( two different threads ).

Basically the output must be something like 0, 1, 2, 3, 2, 3, 4, 3, 4, 5, 6, 5 ,6, 7 ........................

Here is all of my classes. Please help me i am real stuck !!!









 
                            
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is the results.

it is something like 0,1,1,0,1,0,0,0,1,1,1,0 ..................

i need something like 0,1,2,3,4,3,4,5,6,5,6,7,8,7,8.............

add 1, sleep/wait for 250ms, sub 1, sleep/wait for 500ms ................................

 
Henry Wong
author
Marshal
Pie
Posts: 21214
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alexis Kitsios wrote:
add 1, sleep/wait for 250ms, sub 1, sleep/wait for 500ms ................................


Hint #1: There are two threads. You need to envision the two threads independently.

Hint #2: A sleep() method call for 250ms followed by a wait() method call for 250ms doesn't mean that the thread is blocked for 500ms. The wait() method call can wake up earlier if it gets a notification.

Henry
 
                            
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. how ???

2. It is not necessary 250 + 250 = 500. I just need blocked for 500ms .
 
Henry Wong
author
Marshal
Pie
Posts: 21214
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alexis Kitsios wrote:
2. It is not necessary 250 + 250 = 500. I just need blocked for 500ms .



Never mind. I just noticed that addNumber() and subNumber() are endless loops, so the sleep() never executes... only the wait() executes.

New hint. What are the chances of the subtractor waiting the full 500ms? Or do you think it will get a notification before that?

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic