CS 235 - Week 9 Lecture - 2015-10-19
Intro to Threads/Multithreading in Java
* 14.1-14.3, 14.5.15, 14.11, 14.11.1, 14.11.3
* thread - lightweight process
* another definition: a thread as a flow of control
within a program
* a Java thread is indeed lightweight -- it
can share a single address space with other
threads
* Java has had supporting for multithreading
as part of the language itself from its
beginning;
* (but some of the early Thread methods are
now deprecated, as we'll discuss)
* there are at least 2 ways of setting up
independent threads,
BUT one of these is preferred, and that's
the approach we're going to take;
* SO: how can this be done?
* we'll write a class implementing the interface
Runnable
* ...and such a class must then implement a
method named run
void run()
...where you put the actions for the desired thread
* Here is the course text's approach to this:
0. You decide you have a task that you'd like to
have done in its own flow of execution, its own
lightweight process
1. Place the code for that task into the run method
of a class implementing the Runnable interface
e.g.,
class MyRunnable implements Runnable
{
...
public void run()
{
// desired task's code
}
}
2. Construct an instance of this class
Runnable thisRunnable = new MyRunnable();
3. Construct a Thread instance from your
Runnable instance:
Thread myThread = new Thread(thisRunnable);
* want to specify a name for your new
Thread instance?
use the Thread constructor with 2
arguments, first of type Runnable,
and second, the desired Thread name,
of type String;
4. Now you can start your new thread with:
myThread.start();
(this will start up a new thread AND
as part of this, call your Runnable's
run method!)
(DON'T call the run method,
THAT will execute your task in the CURRENT
thread, NOT in a new thread!)
* FUN FACTS:
* Thread has a static method called
sleep, that expects a desired number
of milliseconds, and it pauses the
currently-running thread
for approximately that many
milliseconds
* HOWEVER: sleep MIGHT throw
an InterruptedException, which
happens to be a CHECKED exception,
one which MUST either be caught,
or thrown to the next level;
* Thread also has another static method,
currentThread, that returns a reference to
the currently-running thread;
...and you can get a thread instance's
name with its metho getName