Launch thread is just another user thread

Java programs always begin with a main method, called in a user thread.

There are two kinds of threads in Java. They are distinguished soley by how they affect program termination:

A program terminates when there are no more user threads left to execute.

In addition, all user threads are created equal. In particular, the first user thread created upon launch of a program has no special status, and its termination does not necessarily imply that the entire program will terminate.

Example

The FlightSimulator class exists only to launch two other (user) threads. The thread which launches FlightSimulator itself quickly ends, but the program still continues, since there are two other user threads still running.

Output from a sample run of FlightSimulator:

Running Flight Simulator.
Terminating the original user thread.
Running Charles de Gaulle Airport.
Charles de Gaulle Has Available Runway: false
Flight 8875: waiting for runway...
Charles de Gaulle Has Available Runway: true
Flight 8875: taking off now...
Flight 8875: flying now...
Charles de Gaulle Has Available Runway: false
Charles de Gaulle Has Available Runway: true
Charles de Gaulle Has Available Runway: false
Charles de Gaulle Has Available Runway: true
Charles de Gaulle Has Available Runway: false
Charles de Gaulle Has Available Runway: true
Charles de Gaulle Has Available Runway: false
Charles de Gaulle Has Available Runway: true
Charles de Gaulle Has Available Runway: false
Flight 8875: waiting for runway...
Charles de Gaulle Has Available Runway: true
Flight 8875: landing now...
Charles de Gaulle Has Available Runway: false
Charles de Gaulle Has Available Runway: true


/**  Builds and starts threads for Airport and Airplanes. */
public final class FlightSimulator {

  public static void main(String... arguments) {
    System.out.println("Running Flight Simulator.");

    //build an airport and start it running
    Airport charlesDeGaulle = new Airport("Charles de Gaulle");
    Thread airport = new Thread(charlesDeGaulle);
    airport.start();

    //build a plane and start it running
    Thread planeOne = new Thread(new Airplane(charlesDeGaulle, "Flight 8875"));
    planeOne.start();

    //notice that this user thread now ends, but the program itself does
    //NOT end since the threads created above are also user
    //threads. All user threads have equal status, and there
    //is nothing special about the thread which launches a program.
    System.out.println("Terminating the original user thread.");
  }
} 



See Also :
Objects communicating across threads
Use System.exit with care
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -