An application that creates an instance ofThreadmust provide the code that will run in that thread. There are two ways to do this:Notice that both examples invoke
- Provide a
Runnableobject. TheRunnableinterface defines a single method,run, meant to contain the code executed in the thread. TheRunnableobject is passed to theThreadconstructor, as in theexample:HelloRunnablepublic 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. TheThreadclass itself implementsRunnable, though itsrunmethod does nothing. An application can subclassThread, providing its own implementation ofrun, as in theexample:HelloThreadpublic class HelloThread extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new HelloThread()).start(); } }Thread.startin order to start the new thread.Which of these idioms should you use? The first idiom, which employs a
Runnableobject, is more general, because theRunnableobject can subclass a class other thanThread. The second idiom is easier to use in simple applications, but is limited by the fact that your task class must be a descendant ofThread. This lesson focuses on the first approach, which separates theRunnabletask from theThreadobject that executes the task. Not only is this approach more flexible, but it is applicable to the high-level thread management APIs covered later.The
Threadclass defines a number of methods useful for thread management. These includestaticmethods, which provide information about, or affect the status of, the thread invoking the method. The other methods are invoked from other threads involved in managing the thread andThreadobject. We'll examine some of these methods in the following sections.