/** This program is intended to be used with the book "Java 6 -- Java 6 -- What 
 * Do You Want To Do?" by Steven P. Warr and is distributed free of charge and 
 * without and expectations of remuneration.  Chapter APP   NOTE all program 
 * names begin with the title of the chapter in which they are intended to be 
 * used.   Copyright 2010 Steven P. Warr All rights reserved.
 *
 *These classes demonstrate threads and the unpredictability of which thread
 *sequence will execute.   Note that the start () method in an applet is not
 *necessary and the program executes the same way without it.  
 *
 *Your mission: Display the sequence 1 2 3 chronologically 
 *
 *Threads in an applet.
 */

import java.applet.Applet;
import java.awt.*;
public class App04 extends Applet  
{
   private Button start;

   public void init()
   {
      Graphics g = getGraphics();
      
      Oval1 o1 = new Oval1(g);
      o1.start();
      Oval2 o2 = new Oval2(g);
      o2.start();
      Oval3 o3 = new Oval3(g);
      o3.start();
   }
}
class Oval1 extends Thread
{
	private Graphics g;
	private int x = 1,step = 1;
	public Oval1(Graphics gr)
	{
		g = gr;
	}	
   public void run()
   {
   	 g.setColor(Color.red);
     g.drawString("Thread 1  red >    green <" , 50,30);
	 while(true)
	 {
	  if (step > 0 )
	      g.setColor(Color.red);
      else
	      g.setColor(Color.green);
	      
	  g.fillOval(x*20,50,20,20);
	  g.drawString("1",x*30,290);
	  x+=step;
	  if (x > 45 || x < 1 )
	      step *= -1;
	  try
         {
            Thread.sleep(500);
         }
      catch (Exception e){}
    }
    }        
}
class Oval2 extends Thread
{
	private Graphics g;
	private int x = 1,step = 1;
	public Oval2(Graphics gr)
	{
		g = gr;
	}	
   public void run()
   {
   	 g.setColor(Color.blue);
     g.drawString("Thread 2   blue >    yellow <" , 50,130);
 	 while(true)
	 {
	  if (step > 0 )
	      g.setColor(Color.blue);
      else
	      g.setColor(Color.yellow);
	      
	  g.fillOval(x*20,150,20,20);
	  g.drawString("2",x*30 + 10,290);
	  x+=step;
	  if (x > 45 || x < 1 )
	      step *= -1;
	  try
         {
            Thread.sleep(50);
         }
      catch (Exception e){}
    }
    }        
}
class Oval3 extends Thread
{
	private Graphics g;
	private int x = 1,step = 1;
	public Oval3(Graphics gr)
	{
		g = gr;
	}	
   public void run()
   {
   	 g.setColor(Color.magenta);
     g.drawString("Thread 3  cyan >  Magenta <" , 50,230);
  	 while(true)
	 {
	  if (step > 0 )
	      g.setColor(Color.cyan);
      else
	      g.setColor(Color.magenta);
	      
	  g.fillOval(x*20,250,20,20);
	  g.drawString("3",x*30 + 20,290);
	  x+=step;
	  if (x > 45 || x < 1 )
	      step *= -1;
	  try
         {
            Thread.sleep(50);
         }
      catch (Exception e){}
    }
    }        
}
 