17
version 2002-04-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 Java the UML Way http://www.tisip.no/JavaTheUMLWay/ Threads What is a thread? page 2-4 Dividing time between threads page 5-6 Threads with Runnable page 7 Thread states page 8 Communication between threads page 9-10 Locks and synchronization page 11-12

Threads

  • Upload
    balin

  • View
    43

  • Download
    0

Embed Size (px)

DESCRIPTION

Threads. What is a thread?page 2-4 Dividing time between threadspage 5-6 Threads with Runnablepage 7 Thread statespage 8 Communication between threadspage 9-10 Locks and synchronizationpage 11-12 wait(), notify() and notifyAll()page 13 Interruptspage 14-17. - PowerPoint PPT Presentation

Citation preview

Page 1: Threads

version 2002-04-17Only 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

Java the UML Wayhttp://www.tisip.no/JavaTheUMLWay/

Threads

What is a thread? page 2-4Dividing time between threads page 5-6Threads with Runnable page 7Thread states page 8Communication between threads page 9-10Locks and synchronization page 11-12wait(), notify() and notifyAll() page 13Interrupts page 14-17

Page 2: Threads

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

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.

Page 3: Threads

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

Processes and Threads

process 1 process 3process 2

thread 1

thread 2thread 3

thread 1

thread 2

thread 1

Each process gets itsProcess ID (PID)

Page 4: Threads

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

initialization

an operation does paralleloperation

awaits resultsfrom thread 2

thread 1

new operations

thread 2fork line

join line

Running of two Threads

Page 5: Threads

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

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.

Page 6: Threads

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 6

AnExampleclass 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(); }}

...

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 3 3 3 3 3 3 3 3 5 4 1 2 5 4 1 2 5 4 1 2 5 4 1 2 5 4 1 2 5 4 1 2 41 2 41 2 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 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 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 5 5 5 5 5 5 5 5 5 5 5 5 ...

Printout:

Page 7: Threads

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

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(); }}

Page 8: Threads

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

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.

Page 9: Threads

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

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.

Page 10: Threads

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

Join between Threads

the thread finishes

the thread wants to“join” with thread 2, and

sends the message join()

thread 1 thread 2

thread 1 continues, join()returned when thread 2

ended

Page 11: Threads

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 11

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 1

thread 2

thread 3

object which thethreads use

method call

method call method call

printSequence();

Show program listing 16.3 with printout, pp. 511-513

Page 12: Threads

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

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.

Page 13: Threads

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

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.

Page 14: Threads

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

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

Page 15: Threads

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, 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.

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 } }}

• The classes Sleeper and Counter are shown on the following pages.

• The main program is the same:

Page 16: Threads

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 Sleeper

class Sleeper extends Thread { public void run() { while (true) { 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 InterruptedException is

thrown

always false because the program flow gets here without being interrupted, either because of exception

handling or because 2000 ms is passed

Page 17: Threads

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

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());

System.out.println("interrupted(0): " + Thread.interrupted());

// First call should have cleared it. System.out.println("interrupted (1): " + Thread.interrupted()); } }}

true if interrupt before addition is

finished

always false because interrupted() unsets the

interrupted flag

Read chapter 16.8, and solve the problem at the end.

Example Counter