Implementing the Runnable Interface

Class PrintTask (Fig. J.12) implements Runnable (line 5), so that multiple PrintTasks can execute concurrently. Variable sleepTime (line 7) stores a random integer value from 0 to 5 seconds created in the PrintTask constructor (line 17). Each thread running a PrintTask sleeps for the amount of time specified by sleepTime, then outputs its task’s name and a message indicating that it’s done sleeping.

 1   // Fig. J.12: PrintTask.java 2   // PrintTask class sleeps for a random time from 0 to 5 seconds 3   import java.util.Random; 4  5   public class PrintTask implements Runnable 6   { 7      private final int sleepTime; // random sleep time for thread 8      private final String ...

Get Android™ How to Program, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.