View RSS Feed

My Java Tips

Simple Thread Examples

Rate this Entry
by , 11-01-2011 at 05:58 PM (1240 Views)
I will present an example that will show start, stop, suspend, and resume threads. It uses the Runnable interface.


Such threads are useful for things like controlling animation sequences or repeatedly playing audio samples. This example uses a thread that counts and prints a string every second. The thread starts when the applet is initialized. It continues to run until the user leaves the page. If the user returns to the page, the thread continues from where it left off. This allows applets to retain their states while the user is away.

Java Code:
import java.lang.Thread;
import java.applet.Applet;

public class InfiniteThreadExample extends Applet implements Runnable
{
  Thread myThread;

  public void init()
    {
      System.out.println("in init() -- starting thread.");
      myThread= new Thread(this);
      myThread.start();
    }

  public void start()
    {
      System.out.println("in start() -- resuming thread.");
      myThread.resume();
    }

  public void stop()
    {
      System.out.println("in stop() -- suspending thread.");
      myThread.suspend();
    }

  public void destroy()
    {
      System.out.println("in destroy() -- stoping thread.");
      myThread.resume();
      myThread.stop();
    }

  public void run()
    {
      int i=0;
      for(;;)
        {
          i++;
          System.out.println("At " + i + " and counting!");
          try {myThread.sleep(1000);}
          catch (InterruptedException e ) {}
        }
    }
}
Output:


in init() -- starting thread.
At 1 and counting!
in start() -- resuming thread.
At 2 and counting!
At 3 and counting!
At 4 and counting!
At 5 and counting!
At 6 and counting!
At 7 and counting!
At 8 and counting!
At 9 and counting!
in stop() -- suspending thread.
in destroy() -- stoping thread.

Submit "Simple Thread Examples" to Facebook Submit "Simple Thread Examples" to Digg Submit "Simple Thread Examples" to del.icio.us Submit "Simple Thread Examples" to StumbleUpon Submit "Simple Thread Examples" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments