Home | Java Menu | Java Applets | Java Tips | E-mail Us
View Java Applet


/* ThreadSample.java
  *
  * A Java Applet demonstrating one way of creating and running threads by
  * implementing the Runnable interface.
  *
  * Note: This is an example of creating simple threads in Java.  It does not include
  * features such as the wait(), notify(), and notifyAll() methods from the Object
  * class.  In a normal environment, one thread usually has to wait for another
  * thread to complete its task before it can perform.  Ideally, the threads need 
  * to communicate between each other when they have completed their task, or
  * else a deadlock could occur.
  *
  * Khim Theng
  * khim_theng@completeesolutions.com
  *
  * Last modified on 05/16/2000
  */

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

public class ThreadSample extends Applet implements Runnable
{
    int xPosition;
    int yPosition;
    String threadName = "Thread";

    //Declare three threads
    Thread t1;
    Thread t2;
    Thread t3;

    public void init()
    {
        setBackground(Color.white);
    }

    public void start()
    {
        //Create three new threads
        t1 = new Thread(this);
        t2 = new Thread(this);
        t3 = new Thread(this);

        //Assign names to the threads
        t1.setName("Thread 1");
        t2.setName("Thread 2");
        t3.setName("Thread 3");

       //Make the threads Daemon threads, so the threads end when main ends.
        t1.setDaemon(true);
        t2.setDaemon(true);
        t3.setDaemon(true);

        //Set priority on the threads.  The higher the number, the higher the priority.
        t1.setPriority(2);
        t2.setPriority(7);
        t3.setPriority(5);

        //Start execution of the threads.  start calls the run method.
        t1.start();
        t2.start();
        t3.start();
    }  //End of start

    public void run()
    {
        for (int i = 0; i <= 5; ++i)
        {
            //Get the name of the thread and assign it to string threadName
            threadName = Thread.currentThread().getName() + "   " + i;
            repaint();  //Call paint to output the name
            try
            {
                Thread.sleep(400);  //Sleep for 400 milliseconds
            }
            catch (InterruptedException ie)  {  }
        }
    }

    public void update(Graphics g)
    {
        paint(g);
    } 

    public void paint(Graphics g)
    {
        g.drawString(threadName, xPosition, yPosition);  //Draw the string in position xPosition and yPosition
        yPosition += 14;
    }

}  //End of ThreadSample
                
View Java Applet

Home | Java Menu | Java Applets | Java Tips | Legal
© 1999-2003 Complete e Solutions, Inc.