Java Reference
In-Depth Information
in memory rather than code within a single program. The Java Virtual Machine
(JVM) controls the threads within a Java program much as the machine operating
system controls multiple processes.
In some JVM implementations, threads are directly assigned to native pro-
cesses in the operating system. Furthermore, in operating systems that support
multiple physical processors, the threads can actually run on different processors
and thus achieve true parallel processing.
Multiprocessing in Java with threads is relatively straightforward and provides
for great flexibility in program design. The JVM handles most of the details of
running threads but your program can influence the sharing of resources and
setting priorities for multiple threads.
8.4.1 Sharing resources
Just as in an operating system, when multiple threads need to share a processor
or other resources, the JVM must provide a mechanism for a thread to pause
and allow other threads the opportunity to run. The two basic designs for context
switching of threads are:
preemptive or time-slicing -give each thread fixed periods of time to run
non-preemptive or cooperative -athread decides for itself when to surrender control
Generally, the preemptive approach is the most flexible and robust. A misbehav-
ing thread cannot hog all the resources and possibly freeze the whole program.
Unfortunately, the context switching design is not specified currently for Java
and so different JVMs do it differently. Thus you should design your multi-
threaded code for either possibility if you expect to distribute your program for
general use.
Forexample, you can explicitly add pauses to your threads to ensure they
share the processing. The static method yield() in the Thread class tells the
currently executing thread to pause momentarily and let other threads run. The
static method sleep(long millis) ,where millis is in milliseconds, tells
the currently executing thread to pause for a specific length of time. There is
also the overloaded version method sleep(long millis, int nanos) ,
where the sleep time equals millis in milliseconds plus nanos in nanosec-
onds. (Most platforms, however, cannot specify time that accurately.) With these
two methods, you can ensure that when your program runs in a non-preemptive
environment, the threads will release control at suitable points in the thread code.
The resources needed for each thread is another aspect of multiprocessing
to consider when creating a high number of threads. The maximum number of
threads depends on the stack space needed per thread and the amount of memory
available. The stack size default is 400 KB. For a 1 gigabyte address space this
Search WWH ::




Custom Search