Java Reference
In-Depth Information
Sidebar 10.1 Java threads
Multithreading is a powerful programming tool that is native in the Java language. It builds on the
concept of “thread”, an execution flow that processes a sequence of programming instructions.
Traditional programming environments are single-threaded, i.e. a program consists in a single
execution flow. In a multithreaded environment, several execution flows are active simultaneously.
An application might run several threads that execute the same sequence of instructions or differ-
ent sequences of instructions simultaneously. The thread mechanism abstracts from the single-
processor nature of the computer hardware and allows the creation of an undefined number of
virtual processors that share the computer's CPU. The operating system schedules the allocation of
the CPU to the active threads transparently. When a thread is created, it is initialized with the code
to execute and the data to process. Code and data are passed to the thread in the form of a class
instance. The programmer builds the simplest multithreaded application in three steps:
■
Implement the class that defines data and code to be executed (e.g. class
Clock
). This class
should implement the
Runnable
interface that requires the programmer to write the code for the
run()
method. For example, the
run()
method increments a counter every second and displays its
current value on the screen.
■
Define the main class (e.g. class
WatchMaker
) that represents the whole application and
implements the
main()
method.
■
In the
main()
method, create instances of class
Thread
and initialize each of them with a different
instance of class
Clock
. Then, for each
Thread
instance invoke method
start()
.
A thread's execution can be suspended for a predefined time period using the
sleep()
method or
for an undefined time period using the
wait()
method. The execution can be resumed explicitly
using the
notify()
method. For more details on Java threads and synchronization refer to a Java
reference manual.
public class
Clock
implements
Runnable {
long
delay;
int
tick
#
0;
String name;
public
Clock(String n,
long
d) {
name
#
n;
delay
#
d;
}
public void
run() {
while
(true)
try
{
tick
!!
;
System.out.println(name
!
" : "
!
tick);
Thread.sleep(delay);
}
catch
(InterruptedException ie){}
}
}
public class
Application {
public static void
main(String[] args) {
Thread t1
#
new
Thread(
new
Clock("Clock A", 100));
Thread t2
#
new
Thread(
new
Clock("Clock B", 500));
t1.start();
t2.start();
}
}