It is often the case that a computer program needs to do more than one thing simultaneously. For example, a program might want to do some computation
while
waiting for user input. If the user presses a key, the program should perhaps stop the other task it is performing and respond.
A computer with a single CPU can run multiple programs simultaneously; for example, your computer might be playing audio in the background while you are actively inserting text into a Word document. Your operating system has a
scheduler
that determines which program, or
process
, gets to run at any given time.
Within a single process,
threads
are the programming abstraction that allow concurrent execution of several different tasks. Your programs all have a main thread that begins executing when your program starts. Your main thread may also spawn other threads that execute concurrently. Again, you can conceptually think of the threads executing at the same time, but really a scheduler is deciding which thread gets to run at any given time. As a result, you cannot guarantee how the individual statements in each thread are interleaved.
Java Threads
In Java, the typical approach to creating a thread is as follows:
-
Create a class that implements the
Runnable
interface as shown the examples T1 and T2 below.
-
An object of type Runnable must implement the method
public void run()
. Often, the body of this method contains a loop that executes repeatedly. The example below uses
while(true)
, which means that the loop will run forever. A better approach is to use a boolean variable (for example, running) and continue to execute as long as the variable is true. You can also provide a
stop
method in your Runnable class that changes the value of the variable to false and stops execution of the thread.
-
To create a Runnable object and call its run method, you create a new object of type
Thread
. The
Thread
constructor takes as input an object of type
Runnable
. Once you have created the Thread object, you invoke the Runnable's run method by calling the
start
method on the Thread object.
|