Threads: Defining and Starting a Thread
Defining and Starting a Thread
//with Runnable object
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();
}
}
// with Thread subclass
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new HelloThread()).start();
}
}
- An application that creates an instance of Thread must provide the code that will run in that thread.
- First way to provide code that will run in the thread: 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.
- Second way to provide code that will run in the thread: 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.
- Both options invoke Thread.start in order to start the new thread.