Instructional Material: Exercise: Using Multiple Threads

If you have not read the lesson on multi-threading in the Advanced Topics unit, do so before continuing.

We are going to look at a simple example of multi-threading (also called multi-tasking). We are going to take the Tank Drive exercise and modify it to have the driving part of the code run in a new thread. The idea is that the main thread can focus on other tasks, perhaps more important or complex and the simple driving code can be in a thread, executing separately from the main thread and just taking care of driving. Create a new class called DriveTankMT and put the following code in it:

The first thing to notice is the use of a private inner (nested) class DriveThread, that extends java.Thread. That class will hold all of the thread specific code, which in the simple case, is just the run() method. Our code to handle driving is in the run() method. We use an inner class because it is simpler and makes accessing the members of the main class easier. Here is more on inner classes.

In the main class at start up we create an instance of the driving thread class and use that instance reference variable to control the thread. Control is pretty simple, when we want to start driving we call the start() method on the thread class and when we want driving to stop we call the interrupt() method on the thread class. While running, the DriveThread class handles the mapping of joystick input to motor power settings and you can see the main thread goes about other business.

In this example, the variables leftY and rightY are shared between the main thread and the driving thread. To reduce concurrency problems, only the driving thread sets the values of leftY and rightY. The main thread only reads from these variables. If high accuracy were needed, we would put the volatile modifier on the definition of leftY and rightY. This is adequate for simple situations. More complex data sharing between threads and a more detailed exploration of concurrency is beyond the scope of this lesson but you can read more about threads and concurrency here.

 

Material Type: 
Lecture/Presentation
Education Level: 
Middle School
High School
Focus Subject: 
Computing / Computer Science
Robotics Software
HW Platform: 
Tetrix
SW Platform: 
Java
Interactivity Style: 
Mixed
Audience: 
Learner