//  FAMOUS DIGITAL CLOCK APPLET.
//  (Based on digital.clock applet from Sun Corp.)
//   Modified by J. Auciello,  Prof. CIS,  LATTC.
//   JULY.17.1999.
//   athread.java
//
//  Intro to Threading.
//  Threaded version -- Digital Clock. 
//  operates 2 threads concurrently. 
//      
/*
DEFINITIONS:
    THREAD          = SINGLE FLOW OF CONTROL WITHIN A PROGRAM.
                      runs on its own while rest of program
                      does other tasks.  Demonstrates
                      "Multi-tasking" ability of Java.

   MULTI-THREADING =  MULTIPLE FLOWS OF CONTROL WITHIN PROGRAM.
                      Concurrent Activities.
                      Multi-Threads are not Parallelly-Processed.
                      Each Thread competes for CPU time.
                      Tasks with "POTENTIALLY LONG WAITS" should
                      run as "THREADS"!
                      When WAIT occurs, JAVA can shift to another
                      task for execution.

    Topics:
        Threading (allowing multi-threading)
        Tracing Program Flow.
        Applet Program Cycle
        start(), run(), stop() methods.
        Text -- setColor(Color.xxx)
        Background Colors -- setBackground(Color.xxx)
        Standard color names and RGB values.
*/
       import corejava.*;         // libraries necessary to operate.
       import java.applet.*;
       import java.awt.*; 
       import java.awt.event.*;
       import java.awt.Color;
       import java.awt.Font;
       import java.awt.Graphics; 
       import java.io.*;
       import java.lang.Math;
       import java.lang.String;
       import java.lang.Thread;
       import java.lang.ThreadGroup;
       import java.net.*;
       import java.util.*;
       import java.util.Date;

// extends runnable attributes to this applet (athread) 
      public class athread extends java.applet.Applet implements Runnable
      {
// define all global variables.
        Font   theFont = new Font("TimesRoman",Font.BOLD,16);
        Date   theDate;
        Thread runner;                 // the thread address is in runner.
        int    x = 10;

// if there is no thread, start one, shift to run().
      public void start()
        { System.out.println("runner @ start() time = " + runner);
           if ( runner == null);
              { runner =  new Thread(this);
                runner.start();
              }
         }

//  control "c"  takes control here.
      public void stop()
        { if (runner != null);    // if not equal null, make it = null.
            { runner.stop();
              runner = null;
              System.out.println("runner @ stop() time  = " + runner);
            }
        }

// infinite loop, gets and converts date, takes 1 second nap,
// Java Run System leaves this routine briefly to attend to
// paint() routine.
      public void run()
       { while (true)
         { theDate = new Date();         // get date from system. 
           repaint();
             try
              { System.out.println("Timer Thread is running -- (timer) run() method");
                System.out.println("                 run(1) = " + runner);
                Thread.sleep(1000);
              } //sleeps 10000 msecs.
             catch
              (InterruptedException e)  {}
         }
       }
// try ... catch are explained very well in an "error trapping" example.


// this routine generates results of 2^x (2 raised to the x),
// and displays time, all messages, and results of 2^x.
     public void paint(Graphics g)
       { 
         setBackground(Color.cyan);
         g.setFont(theFont);         
         g.setColor(Color.red);
         g.drawString("Display Thread steals program cycles from timer, paints screen and does computations!", 10,140);

         g.drawString("Serious programming can be done by either thread!",10,215); 

         g.setColor(Color.blue);
         g.drawString(theDate.toString(),10,35); 
         g.drawString("(2) Active Threads Running -- timer (run) & display (paint)", 10,70);

         g.setColor(Color.red);
         g.drawString("Timer Thread runs constantly! ... while (true) loop.",10,105);
         System.out.println("Display Thread is running -- (screen painter) paint() method");
         System.out.println("                 run(2) = " + runner);
       
         
         g.setColor(Color.white);
         g.drawString("Repainting screen with updated time every time paint thread runs",10,245);
         
         g.setColor(Color.red);
         g.drawString("Computations like below:  2 to 10th .. 60th Power",10,165);
         for ( x = 10; x < 61;  x=x+5)
             { double dx = Math.pow(2,x);
               g.drawString("2 to the " + x + " power = "+ dx, 10,190);
               System.out.println("2 raised to the "+ x + " power = " + dx);
             }
         
      
         g.setColor(Color.cyan);
         g.drawString("Display Thread steals program cycles from timer, paints screen and does computations!", 10,140);
                 
        g.setColor(Color.white);
        g.drawString("CIS 790   (Java Programming)   Prof. Auciello   LATTC",10,300);        

       }
     }
      
//
// ==================================================================
// ==================================================================
/*

Program Narrative:

        The Java Run Time Module supports threads.
        This is an operating system feature brought down
        to the program - level.  Very strong feature!
        
        Because this applet has an endless loop [while (true)],
        without "threading", the "while loop" would occupy the CPU,
        not leaving any program cycles to "repaint"  the screen.
        Note "runner" contains thread information.

        'Runnable' interface allow threading.  It requires
        a run() method.  You 'instantiate' this class with
        a 'new' statement.

        Download this source listing,  save it, modify it,
        compile it, and test it.  Only by modifying and
        changing this program, and running it will you
        you achieve full comprehension of 'multi-threading'.
        

         Detailed line-by-line analysis          

1:	 import specific class.
         each java statement ends with  a semi-colon (;).
         'import' accesses Java Library.
         'class'              = template for multiple objects with similar
                                features.
         graphics, font, date = 3 classes that are 'imported' from java.awt
         import java.awt.*    = import all classes in awt.

2:       awt'                 = Abstract Window Toolkit (package)
                                (part of Java class library).
         'instance'           = actual object.
         'instance variable'  = attributes of an object.

3:       (java.util.Date).    = 'util' is a Java library function.
4:	
5:       public               = access control  (vs. 'private' / 'protected')
         class                = Keyword used to define "Digital Threads".
         athread              = Name of the Class.
         extends              = "extends characteristics to ..."
         java.applet.Applet   = defines 'DigitalThreads' as an applet.

6:       implements Runnable  = required for 'threading'
                                supports 'runnable interface in the applet.
                                enables 'run()' to be called on your
                                instances.
                                Any classes that use "threads" must
                                include "Runnable".

8:       theFont              = an object representing current font.
9:       theDate              = an object representing current date.
                                [both are 'basic instance variables']

10:      'Thread runner'      = instance variable that holds applet's
                                thread. 'Thread' is a class in Java, not
                                imported.
                                Defines a variable named "runner"
                                of type "Thread".

12:      public void start()  = procedure name that spawns a
                                thread
                     start()  = starts a thread.

13:     runner                = variable name.
        ==                    = Comparison Operator (equal)
        null                  = nothing (self-defining)

14:     new Thread(this)      = creates a new class.
        this                  = refers to the applet itself.
                                links the applet with Runnable Interface
                                with the runner object (see printout
                                of "runner").
15:     runner.start          = runs the thread and calls the run()
                                method.

19:     stop()                = stops a thread.
20:     runner != null        = (runner not equal to null) 
21:     runner.stop()         = 
22:     runner = null         = "if variable 'runner' = null"
25:
26:
27:     public void run()     = what the applet actually does!
        run()                 = triggers actual execution of the applet.
                                does most of the applet work.
                                where animation takes place.

28:     while (true)          = always true (boolean). Never exits.
29:     thedate=new Date()    = replace theDate with new Date. 
                                creates a new instance of the Date class.
                                refreshes Date with current date & time,
                                assigns it to the 'theDate' instance
                                variable.
30:     repaint()             = calls 'repaint' function
31:     try                   = error trapping (error trapping applet)
        Thread.sleep(1000)    = sleeps 1000 msecs  ( 1 second ).
                                sleep() is part of the Thread class.
                                allows user to control the speed of animation.
                      sleep   = "sleep" is a method of the "Thread"
                                class.  Controls program speed.

32:     catch                 = handle exceptions and manage errors.
      InterruptedException e) = 'e' names a method for error handling.

35:     public void paint     = name of graphical method
        g.                    =  name of instance variable

36:     g.setFont(theFont)    =  sets current font

37:     g.drawstring(theDate.tostring(),10,50);
                              = 'tostring()' converts date to a string,
                                 then printed to the screen (updated
                                 every second.
                                 Because paint() is called repeated with
                                 whatever value happens to be in theDate,
                                 the string is updated every second to
                                 reflect the new date. best to calculate the
                                 new objects / instance variables'
                                 date & font) before calling paint().

     COLOR      HEX VALUE       COLOR    HEX VALUE
     ====================       =================
     black      000000          blue     0000ff
     cyan       00ffff          darkgrey 404040
     gray       808080          green    00ff00
     lightgray  cococo          magenta  ff00ff
     orange     ffc800          pink     ffb1b1
     red        ff0000          white    ffffff
     yellow     ffff00

     shortcut:                  red     green   blue
                        black   00      00      00   (darkest)
                        blue    00      00      ff
                        cyan    00      ff      ff   (halfway bet blue  + green)
                        green   00      ff      00
                        dkgray  40      40      40
                        gray    80      80      80   (halfway bet black + white)
                        ltgray  c0      c0      c0
                        magenta ff      00      ff   (halfway bet red   + blue
                        pink    ff      b1      b1
                        orange  ff      c8      00
                        yellow  ff      ff      00   (halfway bet red   + green)
                        white   ff      ff      ff   (lightest)

ASSIGNMENTS:

100 POINTS:     SELECT TEXT AND BACKGROUND COLORS THAT VIVIDLY
                EXPRESS THE PROCESS OF THIS APPLET.
                (note from author.  Some have more talent
                 with art (colors, proportion, aesthetics,
                 visual communication) than others.
                 
                 Give this a try to develop your latent skills,
                 my category, or demonstrate your right-hemisphere
                 skills.!)   When you can enhance technology
                 with art, you are at the "Performance Level".

100 POINTS:     TRY TO DEVELOP (2) HORIZONTAL BARS THAT MOVE
                ACROSS THE SCREEN.  BASE ONE IN THE RUN() METHOD,
                PASS ITS VALUE TO THE PAINT() METHOD,  AND BASE
                THE OTHER IN THE PAINT() METHOD.
                DRAW BOTH OF THEM ON THE SCREEN.

                ALONG THIS ORDER:

                (RUN    METHOD) |XXXXXXXXXXXXXXXX
                (PAINT  METHOD) |XXXXXXXXXXXXXXXXXXX

         
Note:  I just ran this.  The results are interesting.
       There is a definite winner.  
       Explain why one of these methods wins consistently.



Extra Activities:  
       Try to add a 3rd method (routine) to this applet,
       make it a thread.

       Change the power function to a routine that calculates 100
       Prime Numbers or computes the 1st 100 Fibonacci Numbers
       (starting with 1,1).  Both of these routines are long
       tasks that will all the Java Run System to execute other
       routines such as Paint() and any others that you might add.

Extra Credit (25 points)
       Can you have an infinite loop in the paint thread?
       Explain the answer.


Locate Java Console under "Communicator" on Tool Bar.
Study the messages.
       

Closing Note:
       For sure now, as I develop these lessons, I believe more
       that "High Performance Visual Learning" is the 'fast track'
       to advanced technology.  High Performance means using tools
       like:  Plan-Code-Verify-Modify, based on Deming's Plan-Do-
       Check-Act! and building on a working model by testing one
       modification at a time.  Also have all your tools working,
       like being sure that the browser is actually testing your
       latest mod, by displaying the time at the top of the output,
       so you know that you are testing the latest version.  I also
       use a batch file that edits, compiles, and calls the
       appletviewer.  Listing of this batch file follows this 
       'diatribe'.  
       
       High Performance "Accelerated" Learning emphasizes a large
       amount of time in "Planning".  You must have a clear picture
       in mind of what you are going to do!  Let your mind 
       brainstorm!  THINK! until you see it clearly, then "GO!"

       "Visual Learning", means using a "Glass Box" approach
       (promoted by Prof. "Hap" Peelle) so you can "visualize"
       the internals of a program.  Use the System.outprintln command
       and show intermediate steps (called "tracing") on the screen.
       By making a program a "Glass Box", using the techniques 
       described above, you can nearly "sense" what the program
       is doing.  Get neurons from both Hemispheres firing!
       Use one side to enhance and optimize the other! 

       By attacking Java Programming with an "attitude", and carefully
       building on each step, "glass boxing" the output, you can
       achieve mastery and full comprehension.

       Java and other web-programming languages allow you nearly
       full control of media (getting better all the time) and
       allow you to showcase your work on a 7-24 basis anywhere
       in the world.  This is as "good as it gets!"  This generation
       of programming languages puts you, the programmer, in exactly
       the right position to catch the full impact of technology
       coming at us!  What the internal combustion engine did
       for cars and AC for electricity and Jet Engines for Airplanes
       only presage a little bit what the use of web-based programming
       will do for the way that we live!       

       J.A.  Mon.July.19.1999.  Simi Valley, CA


Listing of c.bat  (edit-compile-test batch file)

REM  C.BAT  BY J. Auciello,  LATTC.
ECHO OFF
copy %1.jav x.x
time
rem echo .. DIRECTORY OF %1.ja*
rem dir %1.ja*
rem echo ... Check that %1 has a .java extension:  If not, save as %1.java
rem pause
c:\windows\command\edit x.x
COPY x.x  %1.java
copy x.x  %1.jav
if exist %1.class echo ... Erasing Previous Version ...
rem if not exist %1.class ... 
if exist %1.class ERASE %1.class
echo ... About to compile  %1.java   ...
pause
javac %1.java
rem COPY %1.java %1.jav
dir   %1.class
echo .. DOES %1.class EXIST with the current date?
pause
rem java  %1
copy  %1.HTM  *.html
COPY  %1.*    C:\
av    %1.html

REM --- END OF C.BAT 



*/