Multithreading

Bruce Eckel’s Thinking in Java Contents | Prev | Next

A
fundamental concept in computer programming is the idea of handling more than
one task at a time. Many programming problems require that the program be able
to stop what it’s doing, deal with some other problem and return to the
main process. The solution has been approached in many ways. Initially,
programmers with low-level knowledge of the machine wrote
interrupt
service routines

and the suspension of the main process was initiated through a hardware
interrupt. Although this worked well, it was difficult and non-portable, so it
made moving a program to a new type of machine slow and expensive.

Sometimes
interrupts are necessary for handling time-critical tasks, but there’s a
large class of problems in which you’re simply trying to partition the
problem into separately-running pieces so that the whole program can be more
responsive. Within a program, these separately-running pieces are called
threads
and the general concept is called
multithreading.
A common example of multithreading is the user interface. By using threads, a
user can press a button and get a quick response rather than being forced to
wait until the program finishes its current task.

Ordinarily,
threads are just a way to allocate the time of a single processor. But if the
operating system supports multiple processors, each thread can be assigned to a
different processor and they can truly run in parallel. One of the convenient
features of multithreading at the language level is that the programmer
doesn’t need to worry about whether there are many processors or just
one. The program is logically divided into threads and if the machine has more
than one processor then the program runs faster, without any special adjustments.

All
this makes threading sound pretty simple. There is a catch: shared resources.
If you have more than one thread running that’s expecting to access the
same resource you have a problem. For example, two processes can’t
simultaneously send information to a printer. To solve the problem, resources
that can be shared, such as the printer, must be locked while they are being
used. So a thread locks a resource, completes its task and then releases the
lock so that someone else can use the resource.

Java’s
threading is built into the language, which makes a complicated subject much
simpler. The threading is supported on an object level, so one thread of
execution is represented by one object. Java also provides limited resource
locking. It can lock the memory of any object (which is, after all, one kind of
shared resource) so that only one thread can use it at a time. This is
accomplished with the
synchronized
keyword. Other types of resources must be locked explicitly by the programmer,
typically by creating an object to represent the lock that all threads must
check before accessing that resource.

More by Author

Must Read