//LED.java by D Mullier 3/2001
//demonstrates a simple Thread by drawing a blinking LED light
import java.awt.*;
import java.applet.*;
import java.lang.Runnable; //step 1
public class LED extends Applet implements Runnable //step 2
{
Thread LEDThread; //step 3
boolean LEDon=true; //I just set this to true so it always blinks
boolean LEDlight=false;
public void init()
{
LEDThread = new Thread(this,"LED"); //step 4
LEDThread.start(); //step 5
}//end init
public void paint(Graphics g)
{//here the paint method is reading a variable that is changed by our thread
//run changes LEDlight every 1/2 second, notice that run explicitly calls repaint()
//which calls paint()
if (LEDlight == true) //LEDon?
g.setColor(Color.red);
else //if not black
g.setColor(Color.black);
g.fillOval(100,100,50,50);
}//end paint
public void run() //step 6
{
for(;;)//loop forever
{
while (LEDon == true)
{
LEDlight = !LEDlight; //flip the LED status
repaint(); //call paint so it draws the LED in its new state
try{//we'll talk about try..catch next week (they are exceptions)
LEDThread.sleep(500); //wait for 500 milliseconds (1/2 second)
}catch(InterruptedException e)
{
showStatus("Thread timed out");
}
showStatus("LED = "+LEDlight);
}//end while
}//endfor
}//endrun
}//end applet |