Threads, Listeners and Events
|
Threads, Listeners and Events
Java ThreadsWhen a Java program starts, there is a single thread running – the main thread. Many of the leJOS classes start extra threads running for various purposes, for example:
User programs can create their own threads by subclassing Thread, and then using the start method to start the thread. In leJOS NXJ 0.7 and later, threads can be created from any class that implements the Runnable interface. Background threads that do not need to terminate in order for the user program to terminate, should be marked as daemon threads by calling setDaemon(true). When using threads, care should be taken with concurrency issues. When data items are accessed by multiple threads, synchronization is necessary to ensure that data is not read when it is in an inconsistent state. leJOS NXJ supports the standard Java synchronization mechanisms: synchronized methods and synchronized statements using a monitor object. As an example of a leJOS thread, consider the Indicators thread in the leJOS StartUpText menu. This is used to keep the display of the battery level up to date, by reading its value every second, and to indicate when the menu is uploading files or doing other communication from the PC:
The main method starts this thread by:
Back to top
Listeners and EventsleJOS implements a listener thread that listens for particular events. The listener thread supports:
Button listeners are used to detect when a button is pressed, whatever your program is doing at the time. To listen for a press of a specific button, you register as listener for that button. Example:
Back to top
|