Runnable object
In this approach, the class implements Runnable interface which defines a single method run. The Runnable object is passed to the thread constructor. Using the Runnable object is the most general approach because the Runnable object can subclass another class other than Thread.public class MyRunnable implements Runnable { public void run() { System.out.println("I am thread!"); } public static void main(String[] args) { Thread t = new Thread(new MyRunnable()); t.start(); } }
Subclass Thread
In this approach, the class extends the Thread class. This is simple to use but limited in the sense that the class must be descendant of Thread.public class MyThread extends Thread { public void run() { System.out.println("I am thread!"); } public static void main(String[] args) { Thread t = new MyThread(); t.start(); } }
0 comments:
Post a Comment