Simple Thread Examples
17 July 2008I 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.
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.
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Simple Thread Examples
Yikes. Thread.suspend(), resume() and stop() have been deprecated for AGES, and really should NOT be used.
Thread.stop(), Thread.suspend() and Thread.resume() are deprecated since jdk 1.2. Nice example to show.