You can create threads in one of two ways: ■ Extend the java.lang.Thread class. ■ Implement the Runnable interface. (Recommended) Here is an example of implementing the Runnable interface. class MyRunnable implements Runnable { public void run() { System.out.println("Important job running in MyRunnable"); } } public class TestThreads { public static void main (String [] args) { MyRunnable r = new MyRunnable(); Thread t = new Thread(r); // Pass your Runnable to the Thread t.start(); } } Create a thread using an anonymous inner-class that implements Runnable. Runnable r = new Runnable() { public void run() { } }; |
Java >