This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes I need help in a synchronization threads exercise  Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "I need help in a synchronization threads exercise  " Watch "I need help in a synchronization threads exercise  " New topic
Author

I need help in a synchronization threads exercise

Alexis Kitsios
Greenhorn

Joined: May 09, 2013
Posts: 3
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 !!!









Alexis Kitsios
Greenhorn

Joined: May 09, 2013
Posts: 3
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
Sheriff

Joined: Sep 28, 2004
Posts: 18546
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Alexis Kitsios
Greenhorn

Joined: May 09, 2013
Posts: 3
1. how ???

2. It is not necessary 250 + 250 = 500. I just need blocked for 500ms .
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18546
    
  40

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
 
 
subject: I need help in a synchronization threads exercise
 
Similar Threads
How to request monitor info on/from a locked object
producer/consumer
Multithread program from khalid mughal
threads
Thread.sleep