80 likes | 217 Views
Using Thread in leJOS. Introduction to thread. A thread is a thread of execution in a program The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. MMN Lab. Thread in leJOS.
E N D
Introduction to thread • A thread is a thread of execution in a program • The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. MMN Lab.
Thread in leJOS • When a Java program starts, there is a single thread running – the main thread • Extra threads in leJOS: • Button and SensorPort start a listener thread if listeners are used • Each Motor has a regulator thread • The Bluetooth class starts a thread to talk to the separate Bluetooth chip • Each Timer object starts a timer thread MMN Lab.
Using the thread • Two approaches: • Inherit from java.lang.Thread • The simple approach (We focus on this one) • Implement the Runnable interface • The flexible approach (need jeJOS 0.7+) • The most important method for Thread is run() • Use start() to run the thread MMN Lab.
Using the thread cont’d • Sample: class using thread MMN Lab.
Using the thread cont’d • Sample: the main function MMN Lab.
Lab5 • Scenario • 1. Use the sound sensor to wait for trigger • 2. Then start 3 threads (including the main() thread) with the following functions: • Thread 1: beep every 0.5 sec • Thread 2: swing the arm by triggering the sound sensor • Thread3: steer by triggering the ultrasonic sensor • 3. Exit the program after pressing ESCAPE MMN Lab.
Lab5 • Hint: • Add a delay time if your program skip step1 • When you encounter a java exception with thread, adding a delay time may be helpful MMN Lab.