Threads
threads

Java Threads
A thread is computer code being executed.
More than one thread can be executed simultaneously (actually interleaved).
The code for the threads can be the same, or different.
Each thread has itÕs own state, sort of.
Threads can share variables, and modify the variables they share.
Programs with > 1 thread are called Òconcurrent programsÓ.

Timing of Threads
Threads donÕt progress in lock-step fashion.
One may be started and another stopped in an unpredictable fashion by the operating system.
This behavior is called asynchronous.

Similar Idea: Processes
A process is also code in execution.
Typically processes donÕt share variables, although limited sharing is possible.
Multiple processes is common in, e.g. UNIX.
Processes are Òheavy weightÓ, threads are Òlight weightÓ.
Weight refers to the cost of switching the processor from one to another.

Why are Threads Useful?
May wish to have multiple activities going on at once.
DonÕt want one activityÕs waiting (e.g. for an event) to stop the other activities.
This is only doable with threads (or processes).

Thread Example
On thread is a computational one, that occasionally needs to wait for input from the outside, say from an input stream of characters.
Another thread may be a graphical user interface, responding to mouse events.
We donÕt want waiting for input to hold up the graphics, or waiting for a click to hold up the computational thread.

Thread Example
Bouncing Balls Example
Each ball is run by a separate thread.
Each thread can, in principal, be suspended and started independently of the others.
If a ball is ÒclickedÓ in mid-air, it will suspend, and resume if clicked a second time.

Slide 8
Two Ways to Have Threads in Java
extends Thread
Thread is a base class with threading capability.
implements Runnable
Runnable is an interface that requires method
void run()
The latter is preferred, because it does not take away your ability to inherit from another class (multiple inheritance is not allowed in Java).

Using Òimplements RunnableÓ
The class that implements Runnable still needs to contain a Thread.
This Thread is what controls starting and stopping.

Partial Ball Thread Code
Cautions about Threads
Reasoning about concurrent programs is inherently more difficult than reasoning about sequential ones.
They can exhibit non-deterministic behavior, when variables are shared among threads.

Non-Determinism