问题
I want to implement an Anytime k-NN classifier but I cannot find a way to call the "classify(...)" method for a specific amount of time, suspend it, get the available results before the method was suspended, resume the method for a specific amount of time, suspend it, get the available results before the method was suspended, and so on... I use a data structure for getting approximate results. While the algorithm traverses the data structure, it will encounter the actual training data vector, eventually.
public class AnytimeKNN{
public int classify(queryPoint, k){
class_label;
1. Assign an initial value to 'class_label'.
2.while(not actual training data vectors are encountered){
1. traverse the data structure
2. assign a new value to 'class_label'
}
}
}
I want to call the 'classify(..)' method from a main method in the following manner:
- Start the method 'classify(..)'
- Pause the method 'classify(..)' when initial value to 'class_label' is assigned.
- Get the initial label
- Continue the method 'classify(..)' for X amount of time
- Pause the method 'classify(..)'
- Get the new 'class_label'
- Resume the method 'classify(..)'for X amount of time an so on....
Thanks in advance!
回答1:
Sounds like a typical producer-consumer scenario in concurrent programming. In Java, you could solve this using two binary semaphores. One that tells the classifier that it should run and one that tells the main thread to get the next result. The classifier waits on its semaphore until it is triggered by the main thread. The main thread behaves similar.
Of course, there would be other options e.g. using a concurrent queue. The classifier puts its result into the queue and the main thread pulls them out, waiting if there is no new result. This would be my favorite solution but perhaps you have a reason why you want to start and stop the method in fixed time intervals.
来源:https://stackoverflow.com/questions/11603891/start-suspend-resume-suspend-a-method-invoked-by-other-class