View RSS Feed

My Java Tips

Simple Thread Examples

Rate this Entry
by , 11-01-2011 at 06:58 PM (1772 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);

  public void start()
      System.out.println("in start() -- resuming thread.");

  public void stop()
      System.out.println("in stop() -- suspending thread.");

  public void destroy()
      System.out.println("in destroy() -- stoping thread.");

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

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 Submit "Simple Thread Examples" to StumbleUpon Submit "Simple Thread Examples" to Google

Tags: None Add / Edit Tags
Java SE