3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Download Report

Transcript 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Java the UML Way
http://www.tisip.no/JavaTheUMLWay/
Threads
What is a thread?
Dividing time between threads
Threads with Runnable
Thread states
Communication between threads
Locks and synchronization
wait(), notify() and notifyAll()
Interrupts
version 2002-04-17
page 2-4
page 5-6
page 7
page 8
page 9-10
page 11-12
page 13
page 14-17
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 16
What is a Thread?
• When we start a program, we also start a process.
• Several processes (programs) can run seemingly simultaneously
(multitasking), examples: word processing, spread sheet and our own
Java program.
• Also within one program, several tasks can run seemingly
simultaneously, for instance writing to disk and complicated
arithmetic. These small processes within processes are called threads.
• On computers with one microprocessor, the operating system divides
the time between the processes/threads which run seemingly
simultaneously.
• The switch between processes/threads is called context switch.
• The data belonging to one process is saved away at context switch, and
retrieved the next time this process is to run.
• Threads run within other processes, and the threads of a process often
have common data which need not be stored away. Threads are also
called lightweight processes.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 16, page 2
Processes and Threads
process 1
process 3
process 2
thread 1 thread 3
thread 2
thread 1
thread 1
thread 2
Each process gets its
Process ID (PID)
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 16, page 3
Running of two Threads
thread 1
initialization
thread 2
an operation
fork line
does parallel
operation
awaits results
from thread 2
join line
new operations
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 16, page 4
Dividing Time Between Threads
•
Two ways to divide time between threads:
1. The thread itself announces that it can take a break.
2. An external mechanism sets the thread idle by force. (”preemptive
multitasking”)
The mechanism is in the Java interpreter, or the operating system.
•
•
This mechanism is platform dependent.
Modern Java interpreters usually use method 2.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 16, page 5
class NumberPrinter extends Thread {
private int numberToPrint;
public NumberPrinter(int number) {
numberToPrint = number;
}
public void run() {
while (true) {
System.out.print(numberToPrint);
System.out.print(" ");
}
}
}
class ShowerOfNumbers {
public static void main(String[] args) {
NumberPrinter printer1 = new NumberPrinter(1);
NumberPrinter printer2 = new NumberPrinter(2);
NumberPrinter printer3 = new NumberPrinter(3);
NumberPrinter printer4 = new NumberPrinter(4);
NumberPrinter printer5 = new NumberPrinter(5);
printer1.start();
printer2.start();
printer3.start();
printer4.start();
printer5.start();
}
}
AnExample
Printout:
...
3 3 3 3 3
3 3 3 3 3
3 3 3 3 3
2 5 4 1 2
2 5 4 1 2
2 41 2 41
12 5 12 5
5 12 5 12
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
5 5 5 5 5
5 5 5 5 5
5 5
...
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
3 3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 3 3 3 3
3 3 3 3 3 3 3 3 5 4 1
5 4 1 2 5 4 1 2 5 4 1
41 2 41 2 41 2 41 2 41
2 412 5 12 5 12 5 12 5
12 5 12 5 12 5 12 5 12
5 12 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2
2 5 5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5 5 5 5
Chapter 16, page 6
Threads with Runnable
•
•
The constructor of Thread can take
an object as argument. In that case,
that object’s run() method is used.
The object must belong to a class
which implements Runnable.
Useful if our threads need to be
subclasses of another class than
Thread.
class SuperClass {
}
class TheThread extends SuperClass implements
Runnable {
private Thread thread;
public TheThread() {
thread = new Thread(this);
thread.start();
}
public void run() {
while (true) {
System.out.println("Am alive...");
}
}
}
class OurThread {
public static void main(String[] args) {
TheThread thr = new TheThread();
}
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 16, page 7
Thread States
• New
– Before and while start() runs.
• Runnable
– When run() runs. Also when a thread is temporarily stopped because
another thread is allotted running time.
• Blocked
– When the thread gives itself a break by calling sleep() or wait().
– When waiting for IO.
• Dead
– When run() has ended by itself.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 16, page 8
Communication between Threads
• A thread should make sure that other threads get running time.
• But unnecessary context switches should be avoided.
• static void sleep(long milliseconds)
– Class method which sends the calling thread into sleep for the specified
amount of time, can for instance be used to tune the speed of an
animation.
• static void yeld()
– Class method for the calling thread to give itself a break to let other
threads run.
– Very relevant if we can’t be sure that our target platform always does
preemptive multitasking.
• void join()
– Thread A sends the message join() to thread B. Thread A will hold until
thread B finishes.
• void join(long milliseconds)
– The calling thread will only wait the specified amount of time.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 16, page 9
Join between Threads
thread 1
thread 2
the thread
finishes
the thread wants to
“join” with thread 2, and
sends the message join()
thread 1 continues, join()
returned when thread 2
ended
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 16, page 10
Locks and Synchronization
• All the threads of a program can access the program’s objects and
classes about simultaneously.
• What if several threads do updates of the same object about
simultaneously?
• A thread may well be stopped in the middle of a method.
thread 2
thread 3
method call
method call
thread 1
printSequence();
method call
object which the
threads use
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Show program listing 16.3
with printout, pp. 511-513
Chapter 16, page 11
The Solution: synchronized
public synchronized void printSequence() {
System.out.print("1 ");
System.out.print("2 ");
System.out.print("3 ");
System.out.print("4 ");
System.out.print("5 ");
}
• synchronized does not ensure that the method is not aborted at context
switch, but that it is not re-started, or that any other of the object’s
synchronized parts is not started.
• A thread which runs a synchronized method takes the object’s lock,
locking all that is synchronized in the object for other threads.
• synchronized will slow down program execution slightly.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 16, page 12
wait(), notify() and notifyAll()
• Assume that a thread is in a synchronized part of an object.
• If other threads need to be let run, the thread must release the lock:
– void wait()
– void wait(long milliseconds)
• The waiting thread is now in the Blocked state.
• The thread must be awoken by another thread sending a message to the
object:
– void notify()
• awakes an arbitrary thread waiting on this object
– void notifyAll()
• awakes all threads waiting on this object
Show program listing 16.4, pp. 516-518.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 16, page 13
Interrupts
• A thread may idle long because of calls to wait(), sleep() or join()
• This can be interrupted by sending interrupt() to the thread.
• A flag is set (cf. logical variable set to true) saying that the thread is in
a sub-state, it is interrupted.
• If the thread waits
– the exception InterruptedException is thrown
– the interrupted flag is unset
– the handling of this exception decides what happens
• If the thread is not waiting
– exception is not thrown
– should if needed check if it’s interrupted
• if (isInterrupted())…..perhaps finish itself?…
– maybe also unset the interrupted flag
• static boolean interrupted() // note! class method
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 16, page 14
Example, isInterrupted() and interrupted()
Example from Chan, Lee & Douglas: The Java Class Libraries, sec.ed. Vol. I, , Addison-Wesley
1998, ISBN 0-201-31002-3, pp. 1733-1734.
• The classes Sleeper and Counter are shown on the following pages.
• The main program is the same:
import java.util.Random;
class MainSleeper {
public static void main(String[] args) {
Thread t = new Sleeper(); // insert Counter for example 2!
t.start();
Random rand = new Random();
while (true) {
int p = Math.abs(rand.nextInt()%5000);
System.out.println("wake up worker in " + p + "ms");
try {
Thread.sleep(p); // main thread sleeping...
} catch (InterruptedException e) {
System.out.println("main interrupted");
}
t.interrupt(); // … and thereafter awakes the other thread
}
}
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 16, page 15
Example Sleeper
always false because
class Sleeper extends Thread {
public void run() {
InterruptedException is
while (true) {
thrown
try {
Thread.sleep(2000);
System.out.println("sleeper woke up");
} catch (InterruptedException e) {
System.out.println("sleeper interrupted (1): " + isInterrupted());
System.out.println("sleeper interrupted");
}
System.out.println("sleeper interrupted (2): " + isInterrupted());
}
}
}
always false because the program flow gets here without
being interrupted, either because of exception handling or
because 2000 ms is passed
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 16, page 16
Example Counter
class Counter extends Thread {
public void run() {
while (true) {
long sum = 0;
// the amount of loops is adjusted for the speed of the machine,
// should when run output the occasional true
for (int i = 0; i< 1000000 && !isInterrupted(); i++) {
sum += i;
}
System.out.println("Sum: " + sum);
System.out.println("isInterrupted (0): " + isInterrupted());
System.out.println("isInterrupted (1): " + isInterrupted());
true if interrupt before
addition is finished
System.out.println("interrupted(0): " + Thread.interrupted());
// First call should have cleared it.
System.out.println("interrupted (1): " + Thread.interrupted());
}
}
}
always false because
interrupted() unsets the
interrupted flag
Read chapter 16.8, and solve the problem at the end.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 16, page 17