chapter 15

Threads, Date and Time

In this chapter, you will explore the way that Java works with time. You will also discover the way Java works with threads, an important and powerful concept in modern computing.

[H1]Project: the Cue Builder

Today you will build an application that is very handy in multimedia development. You will build a stopwatch that can have a list of cues added to it. When the user clicks on a button, a cue is added. The user can add information to the cue. The cue list can be copied and then pasted into other applications.

***PD: please insert figure jafe1501.pcx screenshot of CueBuilder

[H3][a]Continuous display of minutes and seconds

[H3][b]Cue time generated by program

[H3][c]Tab automatically entered into text area by program

[H3][d]User adds notes to text area

[H3][e]Resets the timer

[H3][f]Adds a cue to the list

[H2]Cue lists and Multimedia projects

Cue lists such as this are important in traditional performing arts and presentation environments, and they are also handy in digital multimedia. In the next chapter, you will take a cue list like this and use it to generate an automatic slide show. It is nice to let the computer handle the timing, rather than messing around with a stopwatch. Here’s one way it might be used: Let’s say you want to synchronize a set of images with an audio file. You will need some way of determining which slides are shown at what time. To get these time values, you might record the audio file, then play it back with this applet running. You might then just keep your mouse on the “add cue” button, clicking each time there will be a cue added. Then, you can go back and edit the text area to tweak the cue times if needed, and to add a description to each cue.

[H1]The Date class

Start by building a simple clock. Take a look at the following source:

***PD: please insert figure jafe1502.pcx source of Clock1

[H3][a]import the util package

This is where the Date class is defined

[H3][b]Create an instance of Date called CurrentTime

The Date object is designed to encapsulate a specific date and time. The actual time and date stored correspond to when the date object was created. It does not change automatically with the passage of time. If you look at the help screen for the date class, you will find that many of its methods have been deprecated, which means they will not be supported by future versions of the compiler. The functionality of these methods is replaced by a new set of classes.

[H3][c]Copy the string value of currentTime to a label

When you convert a date object to a string, you will get a standardized string showing the date and time. Of course, there are ways to improve this formatting, but don’t worry about them yet.

***PD: please insert figure jafe1503.pcx screenshot of Clock1

[H3][a]It works just great!

Does that make you nervous?

***PD: please insert figure jafe1504.pcx screenshot of Clock1 again

[H3][a]This screenshot was taken several seconds later

[H3][b]The time has not changed!

The date object was created only one time, and the value of it was placed in the label only one time. This worked fine for other kinds of values, but the time changes constantly, so you will need to continuously show a new date and time.

[H2]Clocks require endless loops

***PD: please insert figure jafe1505.pcx source of Clock2

[H3][a]Add a loop around date creation, adding to label

[H3][b]true is always true, so loop will never end

[H3][c]This should keep on changing the label

***PD: begin caution

This applet will not work correctly. If you are running it from your browser, you might have to close the browser with a system command (like ctl-alt-delete in Windows)

***PD: end caution

***PD: please insert figure jafe1506.pcx screenshot of Clock2

[H3][a]nothing showed up!

The endless loop you created above was quite rude. It kept on running. Since it never ended, the init method never ended, and the screen was never drawn. The applet never finished initializing, yet it was wildly spinning along, using up system resources. In a less friendly language than Java, such a program could hog up a lot of resources or even hang the entire computer without doing anything useful. You need the functionality of an endless loop, but it needs to be better behaved than this. It should be capable of running in the background so your applet can continue with the initialization, and so it can get on to other business.

***PD: begin note

Any time you have a program that starts to act like this, it might be a good candidate for the techniques in this chapter. Basically, think about using threads when you find the program needing to be able to do more than one thing at a time.

***PD: end note

[H1]Adding a thread

***PD: please insert figure jafe1507.pcx source of ClockThread

[H3][a]Import java.awt

This is surprising, because the clockthread will not have a visual interface.

[H3][b]Import java.util

This gets the date class. The Thread class is part of java.lang, so nothing special needs to be imported to get access to threads.

[H3][c]Constructor requires a label parameter

This will be a reference to a label object in the calling class. ClockThread will never show a label, but it can work with one. It will work with a reference to a label shown by an applet.

[H3][d]While loop goes in run method

The thread class is specifically designed to work in a multitasking environment like modern computers. It can safely incorporate ‘endless loops’ like this one without hogging all the system resources. The thread itself can be started and stopped, so the loop isn’t really endless, but it can be controlled by whatever program created it. The run method of a thread is called whenever the thread is started up, and it can contain ‘endless’ loops safely.

[H1]Calling a thread from an applet

Now that a thread class has been created, look at how it can be incorporated into an applet:

***PD: please insert figure jafe1508.pcx source of CTDemo

[H3][a]Import the ClockThread class

[H3][b]Make an instance of ClockThread

[H3][c]When the applet starts

Applets have a start method which occurs before init. Start also might happen multiple times, if the user leaves the page containing an applet and returns, for example.

[H3][d]Instantiante the looper ClockThread

[H3][e]Start up the ClockThread

this will call the ClockThread’s run method, starting up the loop. Since it is a thread, the loop will go on in the background, so control will come back to this program.

[H3][f]When the applet stops

It is closed by the user, or the user moves to another web page

[H3][g]destroy the ClockThread

Notice that it was not necessary to do anything to the label. Since you passed the label to ClockThread, it did all the work on it.

***PD: please insert figure jafe1509.pcx CTDemo screenshot

[H3][a]It looks just like Clock1.java

[H3][b]At least this time the init seems to have finished

***PD: please insert figure jafe1510.pcx CTDemo screenshot again a few seconds later

[H3][a]This screenshot was taken a few seconds later

[H3][b]The clock is updated correctly

[H1]The Runnable interface

Since threads can be very useful, Java supplies an interface so you can incorporate threading into your programs without having to explicitly create a subclass of thread each time.

***PD: please insert figure jafe1511.pcx source of Clock3

[H3][a]Implement Runnable interface

Now the applet must include a run method

[H3][b]Create the thread

[H3][c]Start the thread up

Check first to make sure it doesn’t already exist. You’ll get an error if you try to generate an existing thread.

[H3][d]Kill the thread when the applet stops

[H3][e]Run the loop with the Thread

The run method will often contain an ‘endless’ loop or some other time-intensive code

***PD: please insert figure jafe1512.pcx screenshot of Clock3

[H3][a]It looks just like CTDemo. It updates the time correctly

[H1]Formatting the time

Now that a clock is working, it makes sense to beautify the display a little bit. So far, you have used the getString() method of the Date object (it is called by String.valueOf()) to return back a string representation of the date. This is serviceable, but you probably want tighter control. You might not want to show the time zone or the date. You might want to display in military time.

Java has a special package called the text package which specializes in text formatting of special objects. It has a great class called SimpleDateFormat.

***PD: please insert figure jafe1513.pcx help screen of SimpleDateFormat main screen

[H3][a]…and this is the simple date format!

Fortunately, the help file contains some samples. It’s always a good idea to try and run the examples if you can, because it will almost always make it easier to understand.

***PD: please insert figure jafe1514.pcx screenshot of Clock4

[H3][a]Same date and time shown four different ways

These were taken directly from the examples on the SimpleDateFormat help screen.

[H3][b]Pattern describing how date will be shown

[H3][c]The current time interpreted through the pattern

***PD: please insert figure jafe1515.pcx source of Clock4 begin and init

[H3][a]import the text package

It contains the SimpleDateFormat class

[H3][b]Create a bunch of labels

[H3][c]Make a simpleDateFormat object. Start it out with a basic pattern

You’ll see what the pattern means in just a moment

[H3][d]Change to a gridlayout

to accommodate all those labels

[H3][e]Create anonymous labels

describing the patterns.

[H3][f]Add the named labels

***PD: please insert figure jafe1516.pcx source of Clock4 run method

[H3][a]Create a Date instance

[H3][b]Apply a pattern to the formatter

[H3][c]Get a String out of the formatter

[H3][d]Send it to the label

[H2]The Patterns

You have probably guessed some of the patterns. ‘h’ stands for a digit of hours, and ‘s’ stands for a digit of seconds, for example. There are a lot of other interesting things going on here as well. Take another look at the help screen for the SimpleDateFormat class:

***PD: please insert figure jafe1517.pcx help screen of SimpleDateFormat chart of digits

Compare this chart with the output of Clock4, and you will begin to see the potential of the SimpleDateFormat class. It can greatly simplify the formatting of dates and times, and help you extract out only the part of the date you want, in a format you want.

[H2]Making a thread sleep

This program now works well even if other programs are running in memory, but it can still be a resource hog. That endless loop is still spinning away, trying hundreds of times a second to update the time. This can cause problems if other programs are running, because their performance will sag. To demonstrate this, try playing some kind of video game while Clock4 is running. The simple applet has a noticeable effect on the performance of your own system. The polite thing to do here is to limit the loop so it does not happen so often.

***PD: please insert figure jafe1518.pcx source of clock5.java run method try block

[H3][a]Something dangerous is about to happen

See below for more information about this

[H3][b]Put the thread to sleep for 500 milliseconds

That’s one half second

[H3][c]If something went wrong, send a message to the console

This code fragment introduces two important new ideas.

First is the concept that a thread can sleep. When you run a thread’s sleep() method, you tell it to take a break so any other processes in the computer’s memory can operate. You can specify how many milliseconds it will sleep. 1000 milliseconds is a second, so 500 milliseconds is a half-second. Since the label will update once per second, you can go at twice that rate and still have reasonably accurate results. The resulting program is much less strain on the system overall.

***PD: begin sidebar

What is this threading thing really?

The essential problem is this: Most computers can’t really do more than one thing at a time. Even when you have eight programs open at a time (I do as I write this) you usually only have one processor, and it can only do one thing at any given moment. Processors have become so fast that they can jump around between all the different programs you have open, and do a decent job of pretending to run many things at once. Each program you run is called a process. Programs can also have extra ‘mini-processes’. These are called threads. When you make a thread, you are specifying that you want the processor to set aside another job that it will put in its normal rotation. A well-behaved process or thread takes up only as much time as it needs, and tries to prevent certain kinds of bad behavior. Much of that functionality is built into Java’s thread object, so you don’t have to worry too much about it as long as you use the Thread class or the Runnable interface. (Thank goodness!)

***PD: end sidebar

[H2]Exception Handling

Programmers tend to be really lax about including error-checking code in their programs. Java plays a dirty trick on lazy programmers. Certain kinds of statements which are known to be dangerous will not compile if there is not some form of error handling surrounding them.