80 likes | 225 Vues
This guide provides an introduction to using threads in leJOS for Java programming. It explains that a thread is a separate path of execution, allowing multiple operations to run concurrently within an application. The Java Virtual Machine (JVM) supports multiple threads, including the main thread and additional threads for listeners, motors, Bluetooth communication, and timers. The guide covers two approaches to creating threads: inheriting from java.lang.Thread and implementing the Runnable interface, with a focus on the latter for flexibility. Sample scenarios illustrate practical applications of threading.
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.