Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Threads 267

program’s interface might respond sluggishly as the data is being loaded.
This can be extremely frustrating to a user.


Two ways to place a task in its own thread include


. Putting the task in a class that implements the Runnableinterface
. Putting the task in a class that is a subclass of Thread


To support the Runnableinterface, the implementskeyword is used when
the class is created, as in this example:


public classLoadStocks implementsRunnable {
// body of the class
}


When a class implements an interface, it indicates that the class contains
some extra behavior in addition to its own methods.


Classes that implement the Runnableinterface must include the run()
method, which has the following structure:


public voidrun() {
// body of the method
}


The run()method should take care of the task that the thread was created to
accomplish. In the stock-analysis example, the run()method could contain
statements to load data from disk and compile statistics based on that data.


When a threaded application is run, the statements in its run()method are
not executed automatically. Threads can be started and stopped in Java,
and a thread doesn’t begin running until you do two things:


. Create an object of the threaded class by calling the Threadconstructor
. Start the thread by calling its start()method


The Threadconstructor takes a single argument—the object that contains
the thread’s run()method. Often, you use the thiskeyword as the argu-
ment, which indicates the current class includes the run()method.


Listing 19.1 contains a Java application that displays a sequence of prime
numbers in a text area. Create a new empty Java file named PrimeFinder,
enter the text from the listing in the file, and save the file.

Free download pdf