Creating responsive user interfaces
As stated earlier, one of the motivations for using threading is to create a responsive user interface. Although we won’t get to graphical user interfaces until Chapter 14, you can see a simple example of a console-based user interface. The following example has two versions: one that gets stuck in a calculation and thus can never read console input, and a second that puts the calculation inside a thread and thus can be performing the calculation and listening for console input.
//: c13:ResponsiveUI.java
// User interface responsiveness.
import com.bruceeckel.simpletest.*;
class UnresponsiveUI {
private volatile double d = 1;
public UnresponsiveUI() throws Exception {
while(d > 0)
d = d + (Math.PI + Math.E) / d;
System.in.read(); // Never gets here
}
}
public class ResponsiveUI extends Thread {
private static Test monitor = new Test();
private static volatile double d = 1;
public ResponsiveUI() {
setDaemon(true);
start();
}
public void run() {
while(true) {
d = d + (Math.PI + Math.E) / d;
}
}
public static void main(String[] args) throws Exception {
//! new UnresponsiveUI(); // Must kill this process
new ResponsiveUI();
Thread.sleep(300);
System.in.read(); // 'monitor' provides input
System.out.println(d); // Shows progress
}
} ///:~
UnresponsiveUI performs a calculation inside an infinite while loop, so it can obviously never reach the console input line (the compiler is fooled into believing that the input line is reachable by the while conditional). If you run the program with the line that creates an UnresponsiveUI uncommented, you’ll have to kill the process to get out.
To make the program responsive, putting the calculation inside a run( ) method allows it to be preempted, and when you press the Enter key you’ll see that the calculation has indeed been running in the background while waiting for your user input (for testing purposes, the console input line is automatically provided to System.in.read( ) by the com.bruceeckel.simpletest.Test object, which is explained in Chapter 15).