JAVATM MASTER

My Threaded Applet

Back to Table of Contents

Here is the code to make simple Applet demonstrating Applet animation using Multiple Threads.

This text is displayed if your browser cannot support Applets.

import java.applet.*;
import java.awt.*;

public class MyThreadedApplet extends Applet 
	implements Runnable{
	boolean ShouldRun = true;
	Thread Runner = null;
	public Color[] colors = {Color.red, Color.orange,
		Color.yellow, Color.green, Color.cyan, 
		Color.blue, Color.magenta};
	public void init(){
		setBackground(Color.yellow);
		add(new Label("Hello World!"));
		add(new Label("I am an Applet"));
	}
	public void start(){
		ShouldRun = true;
		if (Runner == null){
			Runner = new Thread(this);
			Runner.start();
		} 
	}
	public void stop(){
		ShouldRun = false;
		try{
			Runner.join();
		}
		catch(InterruptedException ex){}
		Runner = null;
	}
	public void run(){
		int i=0;			
		while(ShouldRun){
			try{
				Thread.sleep(500);
				setBackground(colors[i]);
				i++;
				if (i >= colors.length) i = 0;
				repaint();
			}
			catch(InterruptedException ex){
			}
		}				
	}
}
The HTML code for this Applet is as follows:

<applet code="MyThreadedApplet.class"
width="150" height="70">
This text is displayed if your browser cannot support Applets.
</applet>

Explanation: In JavaTM API, the Thread class takes a Runnable interface implementing Object as a parameter in its constructor method. You can also extend Thread and implement its run method, because Thread also is a Runnable, it implements Runnable, but its implementation is empty:

public class Thread implements Runnable{
	public void run(){}
	...
}

When a method ends with {} it means it is implemented. To make them useful you need to put something inbetween the curly brackets {}. Otherwise it is just empty implementation. In unimplemented methods they end as in this interface:

public interface Runnable{
	public void run();
} 

with a semicolon (';')

As you can see, Thread needs a Runnable to run, and when the Thread's start method is called it launches the Thread, a separate running process, which executes the code in the run method of the supplied Runnable, or its own run method if none is supplied.

The Applet start method has nothing to do with the Thread start method. The Applet start method is called by the browser after the init method is finished, and the init method is called after the Applet is loaded.

The above is a simple, yet clear example of how to use a Java Thread. It is an expansion of the previous lession: My First Applet

*OracleTM and JavaTM are registered trademarks of Oracle and or its affiliates. Other names may be trademarks of their respective owners.*