Java Reference
In-Depth Information
* will stop the sensor thread. **/
public class DataGetter extends Thread
{
Sensor fSensor;
Outputable fOutput;
int fMaxData = 1000;
int fDataCount = 0;
DataGetter (Sensor sensor, int maxNum, Outputable out) {
fSensor = sensor;
fMaxData = maxNum;
fOutput = out;
}
/** Loop over sensor readings until data buff filled. **/
public void run () {
Random r = new Random ();
while (true) {
String data = fSensor.get();
fOutput.println(fDataCount++ + " . Got: " + data);
// Stop both threads if data taking finished.
if (fDataCount >= fMaxData) {
fSensor.stopData ();
break;
}
// Pause briefly before access the
// data again.
try {
sleep (r.nextInt () % 300);
}
catch (Exception e) {}
}
} // run
} // class DataGetter
8.6 Animations
A popular task for a thread in Java is to control an animation. A thread process
can direct the drawing of each frame while other aspects of the interface, such as
responding to user input, can continue in parallel.
The Drop2DApplet program below illustrates a simple simulation of a
bouncing ball using Java 2D drawing tools. The applet creates a thread to direct
the drawing of the frames of the animation as the ball falls and bounces on the
 
Search WWH ::




Custom Search