Multithreading

Objectives

This week we will look at multithreading. Actually, you have already been exposed to some multithreading in our classroom discussion of GUIs. Now we will look at the topic more generally.

One question is how processes and threads differ. Processes each have their own address space whereas threads share an address space, meaning they can much more easily share data. It is also easier for threads to communicate with each other than it is for processes. In addition, it is usually much more efficient to create and destroy threads than processes. Threads give processes a relatively efficient way of running several tasks at the same time.

The threading detail notes start at thread00.html. Java threading has been evolving and these notes are not completely up-to-date, but they should still work and the major concepts are the same. We will avoid some of the more complex issues at this time since this is your introduction to multithreading. There are also many new multithreading features that were added to Java as of version 1.5. In fact, there are too many to cover in this course such as this. We cover some of the most commonly used new features.

It should be pointed out that JVMs may implement threads in different ways. One of those techniques may be to map the Java threads to threads on the native platform. This requires some compromises and may result in some unexpected consequences. One example is priority levels. A higher priority level indicates that a thread should get a greater percentage of time than its lower priority peers. That sounds good in principle, but a JVM may have fewer priority levels on the native system than Java provides, in which case Java will have to treat some different priorities as the same level. Even worse, on some platforms the priority levels may be essentially ignored. Fortunately, that usually isn't as big of a problem as it sounds like it would be. In case you're wondering, the priority levels go from one to ten in Java. Threads inherit the priority of the thread that created them.

Thread states

Java threads may be in any of the following states:

Concurrency problems

Multithreading demonstrations

HorseRace.java: a simulation with numerous threads