1 / 17

Threads

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 wait(), notify() and notifyAll() page 13 Interrupts page 14-17.

balin
Download Presentation

Threads

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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. 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  3. Processes and Threads process 1 process 3 process 2 thread 1 thread 1 thread 3 thread 2 thread 1 thread 2 Each process gets itsProcess 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  4. Running of two Threads thread 1 initialization thread 2 fork line an operation does parallel operation awaits resultsfrom 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  5. Dividing Time Between Threads • Two ways to divide time between threads: • The thread itself announces that it can take a break. • 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  6. AnExample 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(); } } Printout: • ... • 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 ... 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  7. 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(); } } Threads with Runnable 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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. 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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. 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  10. Join between Threads thread 1 thread 2 the thread finishes the thread wants to“join” with thread 2, andsends the message join() thread 1 continues, join()returned when thread 2ended 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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 2 thread 3 method call method call thread 1 printSequence(); method call object which thethreads use Show program listing 16.3 with printout, pp. 511-513 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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. 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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. 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  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. • 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  16. Example Sleeper always false because InterruptedException is thrown 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 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

  17. 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()); 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. 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 2002The Research Foundation TISIP, http://tisip.no/engelsk/

More Related