Geek 2.0:
As far as yield goes, it's a way to tell the system to pick a thread to run. The system may pick the same thread to run, or it may pick a different thread. I believe that some Java VMs ignore the yield method completely. The Java running on the cRIO DOES pay attention to the yield method, but it may not be necessary (more suggestions later).
The sleep() method is very useful, especially for robots. It tells the system to stop running a thread for a certain number of milliseconds. Consider the original poster's code, minus the camera code and the sleep:
Code:
public void run() {
while (true) {
if (active) {
// camera stuff
} else {
targetFound = false;
}
}
}
This is now a classic "busy loop". It will burn CPU cycles until the system decides to run another thread.
Two classic cases that come up, especially in robotics, are doing a task either periodically or in response to some event.
For the periodic case, you can use sleep() directly, or use the java.util.Timer class.
For the event driven case, there are 3 possibilities:
1) The event comes from Java. One Java thread is trying to tell another Java thread that something happened. The best approach is to use wait/notify.
2) The event is coming externally (from C code or the system), and there is a C function that waits until the event occurs (socket reads, Semaphore.take, etc).
3) The event is coming externally (from C code or the system), and there is NOT a C function that waits until the event occurs. cam.getImage(), for example. In this case, the code needs to "poll" (keep checking) for the event, but do so in a way that doesn't use all the CPU. So this bought us back to a period task.
Finally I'll mention that for Java on the cRIO, Thread.yield calls can be helpful if you have a thread that is doing a lot of straight-line code (not a lot of loop branches), and not any:
- sleep() calls
- notify() calls
- IO
- calls to "blocking external functions" (which include the camera and vision processing functions and talking to the driver station).