I'd go for a simple solution - create int variables in the Thread class to hold the number of threads currently using the track in each direction. Increment the appropriate variable in useTrack and decrement it in exitTrack. Now you have the info necessary to perform the tests specified in your question.
JamesCherrill
Posting Genius
6,337 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,070
No problem. ps: got my method names a little confused - what I meant was put the increment/decrement in enterTrack & exitTrack, then call those from the appropriate places in useTrack. They're obviously there for a reason...
JamesCherrill
Posting Genius
6,337 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,070
Agree about the two ints for number of trains in UP vs DOWN direction. One thing, though-- did your tutor mention to you about thread-safety ? If you have multiple threads accessing some data (here, multiple Trains accessing variables on the same Track), you need to use some mechanism to make sure that the various threads don't try and access the same data at the same time and "clash" with one another. One simple way of doing this is with the synchronized keyword -- I notice that one of your methods is synchronized, but really any methods that refer to the counters/variables on your Track should also be synchronized. (There are other ways of achieving thread-safety, but this is the simplest, and appears to be the one your example code is hinting at.)
neilcoffey
Junior Poster in Training
53 posts since Dec 2008
Reputation Points: 120
Solved Threads: 7
That's a good point about thread safety. I didn't raise the issue in my previous post because the variables in question are ints, and assignments to ints in Java are atomic operations (guaranteed not to be interrupted by other thread). However, the potential for concurrency problems with the Track class in general is real, and synchronizing all the methods would definitely be a good idea.
JamesCherrill
Posting Genius
6,337 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,070