Using Thread in le JOS Introduction to thread

  • Slides: 8
Download presentation
Using Thread in le. JOS

Using Thread in le. JOS

Introduction to thread • A thread is a thread of execution in a program

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 le. JOS • When a Java program starts, there is a single

Thread in le. JOS • When a Java program starts, there is a single thread running – the main thread • Extra threads in le. JOS: – Button and Sensor. Port 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

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 je. JOS 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: class using thread MMN Lab.

Using the thread cont’d • Sample: the main function MMN Lab.

Using the thread cont’d • Sample: the main function MMN Lab.

Lab 5 • Scenario – 1. Use the sound sensor to wait for trigger

Lab 5 • 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 • Thread 3: steer by triggering the ultrasonic sensor – 3. Exit the program after pressing ESCAPE MMN Lab.

Lab 5 • Hint: – Add a delay time if your program skip step

Lab 5 • Hint: – Add a delay time if your program skip step 1 – When you encounter a java exception with thread, adding a delay time may be helpful MMN Lab.