Tutorial 13 (April 5): Range Slider, Multi-threading, A5 multi-threading example
Last week I mentioned a Range Slider class/package which you can use in your programs if you want. It's what I used in the sample UI for the desired ranges for temperature, humidity, and soil moisture.
- Download both the RangeSlider.java and RangeSliderUI.java files (or copy the code and create the files yourself) and put them into a package called "slider."
- import slider.*;
- Use RangeSlider class in your program. You can see a demo here in RangeSliderDemo.java.
The original code is written by Ernest Yu, make sure you cite the author if you use this code.
Today we went over 4 examples, listed below. Definitely take a look at Example 4. When you study for your finals, take 20 minutes and go over Section 19.1, which covers multi-threading quite well.
Example 1: Ping Pong (Multithreading1.zip)
We create two PingPong objects which extend the Thread object, and print out "ping" and "PONG" respectively. The two threads print at different frequencies, and run independent from each other (in parallel).
Example 2: Ping Pong2 (Multithreading2.zip)
The functionality is identical to Ex1, but instead of extending Thread, we create PingPong objects which implement the Runnable interface. The Runnable interface guarantees that you will have a run() method, which is required for Threads. To actually make a thread, you create a new Thread(), passing in your Runnable object as a parameter. You can then start the thread, which will execute the run() method in your object.
Example 3: Banking Error (Multithreading3.zip)
Here we have one joint banking account being shared between two clients. The two clients try to withdraw at the same time, leading to a race condition. A race condition is unpredictable, and depending on which lines of code execute first in the processor, you may have different results running the program multiple times. In this program, if you add the "synchronized" keyword to the withdraw() method, the first client will withdraw $100. The second client will have to wait until the first withdraw is completed, before they are able to check the balance, finding out that there is not enough money left in the account. If the method is not synchronized, the first client may check the balance. Before they complete the withdrawal, the second client will also check the balance. Now both clients believe there is enough money, and both end up withdrawing $100, resulting in a negative balance.
Example 4: Multi-threading in A5 (A5Threading.zip)
This shows you how to implement threading in A5, assuming you followed the suggestion I made to use MVC pattern for each of temperature, humidity, and soil moisture. You can then have each Controller extend Thread, and start all the threads (in the button listener) when the start button is clicked by the user.