Thread
@PrincessOfHeaven (118)
India
1 response
@SunLook (91)
• Portugal
25 Feb 07
An application that creates an instance of Thread must provide the code that will run in that thread. There are two ways to do this::
-Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable exemple:
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!"); }
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start(); }
}
-Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the HelloThread example:
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!"); }
public static void main(String args[]) {
(new HelloThread()).start(); }
}
Notice that both examples invoke Thread.start in order to start the new thread.