Java the UML Way version 2002-04-17 Only to be used in connection with the book "Java the UML Way", by Else Lervik and.

Slides:



Advertisements
Similar presentations
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Advertisements

Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
Thread Control methods The thread class contains the methods for controlling threads Thread() create default thread Thread(target: runnable ) creates new.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Concurrency…leading up to writing a web crawler. Web crawlers.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
1 Multithreading. 2 Threads Program units that execute independently; multiple threads run “simultaneously” Virtual machine executes each thread for short.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
28-Jun-15 Producer-Consumer An example of using Threads.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads Just Java: C10–pages 251- C11–pages 275-
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
© Amir Kirsh Threads Written by Amir Kirsh. 2 Lesson’s Objectives By the end of this lesson you will: Be familiar with the Java threads syntax and API.
Multithreading.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Lecture 4 : JAVA Thread Programming
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Threading Eriq Muhammad Adams J
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Java Thread and Memory Model
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
1 Software Construction and Evolution - CSSE 375 Exception Handling – Chaining & Threading Steve Chenoweth Office: Moench Room F220 Phone: (812)
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Multi-Threading in Java
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Multithreaded applets
Threads in Java Two ways to start a thread
Multithreading / Concurrency
Multi Threading.
Java Multithreading.
Multithreading.
Practice Session 8 Lockfree LinkedList Blocking queues
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Condition Variables and Producer/Consumer
Multithreading.
Condition Variables and Producer/Consumer
Java Based Techhnology
Multithreaded Programming
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 16 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 wait(), notify() and notifyAll()page 13 Interruptspage 14-17

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, 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.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 16, page 3 Processes and Threads process 1process 3 process 2 thread 1 thread 2 thread 3 thread 1 thread 2 thread 1 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 , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 16, page 4 initialization an operation does parallel operation awaits results from thread 2 thread 1 new operations thread 2 fork line join line Running of two Threads

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, 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.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 16, page 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:

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, 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(); }

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, 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.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, 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.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, Chapter 16, page 10 Join between Threads the thread finishes the thread wants to “join” with thread 2, and sends the message join() thread 1thread 2 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 , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, 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 the threads use method call printSequence(); Show program listing 16.3 with printout, pp

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, 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.

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, 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

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, 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

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, 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 , pp 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:

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, 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

Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal. ISBN , John Wiley & Sons Ltd 2002 The Research Foundation TISIP, 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< && !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