Certified Core Java Developer Learning Resources Basics of threads

Learning Resources
 

Basics of threads

Defining and Starting a Thread

An application that creates an instance of Threadmust provide the code that will run in that thread. There are two ways to do this:

  • Provide a Runnableobject. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnableobject is passed to the Threadconstructor, as in the HelloRunnable example:
    
    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 Threadclass itself implements Runnable, though its runmethod 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.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 the Runnableobject can subclass a class other than Thread. The second idiom is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread. This lesson focuses on the first approach, which separates the Runnabletask from the Threadobject 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 include staticmethods, 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 and Threadobject. We'll examine some of these methods in the following sections.

Pausing Execution with Sleep

Thread.sleepcauses the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. The sleepmethod can also be used for pacing, as shown in the example that follows, and waiting for another thread with duties that are understood to have time requirements, as with the SimpleThreadsexample in a later section.

Two overloaded versions of sleepare provided: one that specifies the sleep time to the millisecond and one that specifies the sleep time to the nanosecond. However, these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS. Also, the sleep period can be terminated by interrupts, as we'll see in a later section. In any case, you cannot assume that invoking sleepwill suspend the thread for precisely the time period specified.

The SleepMessages example uses sleepto print messages at four-second intervals:


public class SleepMessages {
    public static void main(String args[])
        throws InterruptedException {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };

        for (int i = 0;
             i < importantInfo.length;
             i++) {
            //Pause for 4 seconds
            Thread.sleep(4000);
            //Print a message
            System.out.println(importantInfo[i]);
        }
    }
}

Notice that maindeclares that it throws InterruptedException. This is an exception that sleepthrows when another thread interrupts the current thread while sleepis active. Since this application has not defined another thread to cause the interrupt, it doesn't bother to catch InterruptedException.

--Oracle
 For Support