Building a Clock Component


What is a Thread?

A thread is a sequence of executable lines of code. Without your necessarily being aware of it, every program we have written has been a thread. When the JVM runs an application, it creates a thread called “main” that executes the application step by step. This thread begins its existence at the opening curly bracket of the public static main(String[]) method. It executes the lines of code as they progress, branching, looping, invoking methods on objects, etc., however the program directs. While it has lines of code to execute, a thread is said to be “running” and it remains in existence. The “main” thread stops running and ends its existence when it runs past the edge of the last curly bracket of the main method.

If we think of our own human body as a “computer”, then an example of a thread in everyday life might be walking. The walking thread begins when you stand up intending to go somewhere. While you are walking, the thread is “running” (pardon the pun). The walking thread ends when you reach your destination and sit down. Another thread might be eating, which begins when you sit down to eat, is running while you continue to chew, swallow and possibly get seconds, and ends when you get up from the table. Or how about a conversation thread which begins when you start conversing with someone, is running as you talk and listen, and ends when both people have stopped talking and listening to each other?

Your body is multi-threaded in that it can and does run more than one thread in parallel or concurrently. Some concurrent threads can run quite independently, having minimal impact on each other. For example, you can converse with someone with whom you are walking because you walk with your legs and converse with your mouth and ears. Other threads are not so independent. For example, conversing and eating. They can and often do run concurrently, but because they both require your mouth’s full participation, there are times when you have to choose between swallowing or speaking. At those times, an attempt to do both simultaneously could have undesirable consequences.

The computer, like our body, is multi-threading. For instance, it can download a file from the internet while you are starting up your photo-editing program. It can play an audio CD while you are saving changes to a document. It can even start up two different applications at the same time. But, as with our bodies, there are some things a computer cannot do concurrently like saving changes to a document that is in the process of being deleted. Last but not least, the JVM is also multi-threading, which means that you can write Java programs that create and run multiple threads. A Java program may create any number of threads with their own independent execution paths, sharing system resources as well as objects created by the program itself.

Threads are instances of the class java.lang.Thread. They are organized into ThreadGroups. In addition to containing Threads, ThreadGroups may contain other ThreadGroups. This tree-like organization exists primarily as a means of supporting security policies that might restrict access from one ThreadGroup to another, but ThreadGroups also simplify the management of threads by providing methods that affect all the threads within a group. When an application is first started, the “main” ThreadGroup is created and given one Thread (named “main”) whose execution path is the “main” method. The application is then free to create and run any number of additional application-specific Threads. When a Thread is constructed, it is contained by the ThreadGroup specified in its constructor, or, if none was specified, by the ThreadGroup that contains the currently running Thread.

Example 16.1: chap16.simple.Main.java

image from book
 1     package  chap16.simple; 2 3     import  utils.TreePrinterUtils; 4 5     public   class  Main { 6       public   static   void  main(String[] args) { 7         TreePrinterUtils.printThreads(); 8      } 9    }
image from book

We will be discussing threads in greater detail soon, but first let’s consider the following program which does nothing at all except to print out all the active threads. Don’t worry how the utility method works, but please pay attention to the output. Figure 16-1 shows the console output from running example 16.1.

image from book

      javac –d classes -sourcepath src src/chap16/simple/Main.java      java –cp classes chap16.simple.Main         ThreadGroup "system" (Maximum Priority: 10)         +--Thread "Reference Handler" (Priority: 10) - Daemon         +--Thread "Finalizer" (Priority: 8) - Daemon         +--Thread "Signal Dispatcher" (Priority: 10) - Daemon         +--Thread "CompileThread0" (Priority: 10) - Daemon         +--ThreadGroup "main" (Maximum Priority: 10)            +--Thread "main" (Priority: 5)

image from book

Figure 16-1: Results of Running Example 16.1

Use the following commands to compile and execute the example. Ensure you have compiled the contents of the Book_Code_Examples/utils folder and placed the resulting class files in your classpath. From the directory containing the src folder:

This minimal program has five threads and two ThreadGroups! At the top of the tree structure is the “system” thread group. It contains four threads as well as the “main” thread group. The “main” thread group contains the “main” thread which was created by the application. The other threads were created by the system to support the JVM. Along with the names of the threads and thread groups, the utility method lists thread and thread group priorities inside parenthesis. Thread priority will be discussed later. If the thread is a daemon thread, that is stated as well. Unlike normal threads, the existence of a running daemon thread doesn’t prevent the JVM from exiting.

Now let’s consider the following minimal GUI program that prints out all the active threads when a button is clicked. While it is running, click the “Print Threads” button to print out all the active threads.

Use the following commands to comile and execute the example. From the directory containing the src folder:

      javac –d classes -sourcepath src src/chap16/simple/Gui.java      java –cp classes chap16.simple.Gui

A click of the “Print Threads” button produces the output shown in figure 16-2 when running in Microsoft Windows 2000 Professional. (Note: The output may be slightly different if running Apple’s OS X.)

image from book

 ThreadGroup "system" (Maximum Priority: 10) +--Thread "Reference Handler" (Priority: 10) - Daemon +--Thread "Finalizer" (Priority: 8) - Daemon +--Thread "Signal Dispatcher" (Priority: 10) - Daemon +--Thread "CompileThread0" (Priority: 10) - Daemon +--ThreadGroup "main" (Maximum Priority: 10)    +--Thread "AWT-Shutdown" (Priority: 5)    +--Thread "AWT-Windows" (Priority: 6) - Daemon    +--Thread "Java2D Disposer" (Priority: 10) - Daemon    +--Thread "AWT-EventQueue-0" (Priority: 6)    +--Thread "DestroyJavaVM" (Priority: 5)

image from book

Figure 16-2: Results of Running Example 16.2

Example 16.2: chap16.simple.Gui.java

image from book
 1     package  chap16.simple; 2     3     import  java.awt.BorderLayout; 4     import  java.awt.Container; 5     import  java.awt.event.ActionEvent; 6     import  java.awt.event.ActionListener; 7 8     import  javax.swing.JButton; 9     import  javax.swing.JFrame; 10 11    import  utils.TreePrinterUtils; 12 13    public   class  Gui  extends  JFrame { 14      public  Gui() { 15        Container contentPane = getContentPane(); 16        JButton button =  new  JButton("Print Threads"); 17        button.addActionListener(new  ActionListener() { 18          public   void  actionPerformed(ActionEvent e) { 19            TreePrinterUtils.printThreads(); 20          } 21        }); 22        contentPane.add(button, BorderLayout.CENTER); 23        pack(); 24       } 25       public   static   void  main(String[] args) { 26         new  Gui().show(); 27       } 28    }
image from book

The “system” ThreadGroup hasn’t changed, but notice that the “main” ThreadGroup contains five threads – none of which is the “main” Thread! These five threads were created by the JVM to support the AWT/Swing framework. What happened to the “main” Thread? Well, as soon as it executed its last line (line 26), it was finished executing its lines of code so it died a natural death. Unless a Swing application explicitly creates new threads, once its main method has completed, the rest of its life will be hosted by the nine threads you see above.

Quick Review

A thread is a sequence of executable lines of code. Threads are organized into a tree structure composed of threads and thread groups. Java programs can create and run more than one thread concurrently. All Java programs are multi-threaded because the JVM and the Swing/AWT framework are themselves multi-threaded.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net