Chapter 12.pptx

advertisement
Chapter 12
Threads and Multiprocessing
Classic Model
• In the classic programming model, there is a single
central processing unit that reads instructions from
memory and carries them out, one after the other.
The purpose of a program is to provide the list of
instructions for the processor to execute. This is the
only type of programming that we have considered
so far.
• Parallel Processing allows the computer to perform
several tasks at the same time.
• In Java, we use threads. They need to cooperate
and communicate.
Threads and Blocking
• A block occurs where a process can’t proceed until
some event occurs.
• Threads make it possible for one part of a program
to continue to do useful work even while another
part is blocked.
• Threads are a vital programming tool even for a
computer that has only a single processing unit.
Multitasking
• Like people, computers can multitask. That is, they can
be working on several different tasks at the same time.
• This used to be the domain of systems programmers,
but increasingly it is something that applications
programmers need to deal with.
• In Java, a single task is called a thread.
• Every Java program has at least one thread.
• In a GUI program, there is at least one additional
thread, which is responsible for handling events and
drawing components on the screen.
Creating and Running Threads
• A thread is represented by an object belonging to
the class java.lang.Thread (or subclass).
• The purpose of a Thread object is to execute a
single method and to execute it just once.
Two ways to program a thread
• Define a subclass of Thread
• define the method public void run()
• call the start() method in the thread object.
• Define a class that implements the interface
java.lang.Runnable.
Thread subclass method
public class NamedThread extends Thread {
private String name; // The name of this thread.
public NamedThread(String name) { // names thread.
this.name = name;
}
public void run() { // prints a message to std out
System.out.println(
"Greetings from thread ’" + name + "’!");
}
}
Starting a thread subclass
NamedThread greetings = new NamedThread("Fred");
greetings.start();
System.out.println("Thread has been started");
• These messages can be printed in either order.
Runnable Method
• The Runnable interface defines a single method,
public void run().
• The Thread class has a constructor that takes a
Runnable as its parameter.
• The advantage of doing things this way is that any
object can implement the Runnable interface and
can contain a run() method, which can then be
executed in a separate thread.
Download