1 Multithreading. 2 Threads Program units that execute independently; multiple threads run “simultaneously” Virtual machine executes each thread for short.

Slides:



Advertisements
Similar presentations
Categories of I/O Devices
Advertisements

Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
Multithreading Horstmann ch.9. Multithreading Threads Thread states Thread interruption Race condition Lock Built-in lock java.util.concurrent library.
Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Concurrency…leading up to writing a web crawler. Web crawlers.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
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.
ThreadThread Thread Basics Thread Synchronization Animations.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
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.
Fundamentals of Python: From First Programs Through Data Structures
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Multithreading.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Java Programming, Second Edition Chapter Seventeen Multithreading and Animation.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Multithreading. Chapter Goals To understand how multiple threads can execute in parallel To learn how to implement threads To understand race conditions.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
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 CSCD 330 Network Programming Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 9 Client-Server Programming.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Concurrency & Dynamic Programming.
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. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
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.
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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Threads in Java Two ways to start a thread
Multithreading / Concurrency
Multi Threading.
Java Multithreading.
CSE 501N Fall ‘09 21: Introduction to Multithreading
Multithreaded Programming in Java
Multithreading Chapter 9.
Lecture 21 Concurrency Introduction
Threads Chate Patanothai.
ITEC324 Principle of CS III
Multithreading.
Multithreading.
Multithreaded Programming
NETWORK PROGRAMMING CNET 441
Threads and Multithreading
CMSC 202 Threads.
Chapter 9 Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

1 Multithreading

2 Threads Program units that execute independently; multiple threads run “simultaneously” Virtual machine executes each thread for short time slice –Thread scheduler activates/deactivates threads –Illusion of threads running in parallel Multiprocessor computers: threads actually do run in parallel

3 Threads vs. processes Processes isolated from each other by operating system –Promotes safety –Makes switching slow Threads run within single process –Fast switching –Multiple threads share memory, can corrupt each other’s data

4 Running threads Define class that implements Runnable interface: public interface Runnable { void run(); } Place code for task in class’s run method Create object of the class Construct a Thread object, supplying Runnable object as argument Call Thread object’s start() method

5 Example public class MyRunnable implements Runnable { public void run() { // thread action goes here } … Runnable r = new MyRunnable(); Thread t = new Thread(r); t.start();

6 Static method Thread.sleep() Every thread should occasionally yield control to other threads Otherwise, have selfish thread – could prevent other threads from making progress Thread.sleep() puts current thread to sleep for specified number of milliseconds A sleeping thread will throw an InterruptedException if terminated; so code using sleep() needs to handle such an exception

7 Expanded example public class MyRunnable implements Runnable { public void run() { try { // thread action goes here Thread.sleep(50); } catch (InterruptedException e) { } } … Runnable r = new MyRunnable(); Thread t = new Thread(r); t.start();

8 Methods start() and run() Thread class has start() method that creates a new thread in the JVM The started thread calls the Runnable object’s run() method The thread terminates when run() method either returns or throws an uncaught exception

9 Running threads in parallel Construct and start two or more Thread objects main() method runs in its own thread; may terminate before the threads it starts Program doesn’t end until all threads terminate

10 Example public class ThreadTest { public static void main(String[] args) { Runnable r1 = new myRunnable(); Runnable r2 = new myRunnable(); … Runnable rn = new myRunnable(); Thread t1 = new Thread(r1); Thread t2 = new Thread (r2); … Thread tn = new Thread(rn); }

11 Subclassing Thread Can extend Thread rather than implementing Runnable, if desired: class someClass extends Thread { public void run() { … try { while (something to do) { // do work sleep(50); } } catch (InterruptedException e) {} } }

12 Scheduling threads Thread scheduler gives no guarantee about order of thread execution Running times vary slightly, depending on what else is going on in the system Order in which each thread gains control is somewhat random

13 Thread states Each thread has a state & a priority Possible states are: –new (before start() is called) –runnable –blocked –dead (after run() exits)

14 Blocked threads Thread enters a blocked state for several reasons; stays blocked until event it is waiting for occurs Reasons for entering blocked state include: –sleeping –waiting for I/O –waiting to acquire a lock –waiting for a notification

15 Scheduling threads Scheduler will activate new thread in each of the following cases: –thread completes its time slice –thread has blocked itself –thread with higher priority becomes runnable Scheduler chooses highest priority threads among those that are runnable Scheduling algorithm system-dependent Priority values not usually under application programmer’s control

16 Terminating threads Thread terminates automatically when run() method of its Runnable object returns Can terminate running thread “manually” by calling method interrupt() –stops thread –releases system resources

17 Checking for interrupted state run() method should occasionally check if its thread is interrupted Can use isInterrupted() method on current thread object; but sleeping thread can’t execute this (because it’s sleeping) – so sleep() method terminates with an InterruptedException if sleeping thread is interrupted – this is why code containing call to sleep() should be surrounded by try/catch block

18 Thread synchronization Threads that share access to a common object can conflict with each other Can result in corruption of a data structure Race condition –effect of multiple threads on shared data depends on order of thread execution –end result (normal vs. corrupted data structure) depends on which thread wins the race Need to ensure that only one thread manipulates shared structure at any given moment

19 Object locks To prevent problems like those caused by race conditions, thread can be set up to lock an object While object is locked, no other thread can lock same object; attempt to do so temporarily blocks other thread synchronizedIn Java, preserve object integrity by tagging sensitive methods with the synchronized keyword

20 Deadlock Occurs if no thread can proceed because every thread is waiting for another to do some work first Common scenario: thread needs to lock an object before checking whether an action can be carried out, then needs to wait to see if check fails Can use wait() method to temporarily block current thread and release object lock; current thread is added to set of threads waiting for object access

21 Unblocking waiting thread When a thread calls wait(), it remains blocked until another thread executes the notifyAll() method notifyAll() unblocks all threads waiting for an object notifyAll() should be called whenever state of object changes in a way that might benefit waiting threads

22 Threads & Animation Animation: shows object moving or changing as time progresses Simple example: animated display of graphical file –reads series of GIFs into array of images –paint routine selects one to display, then update index so next image will be selected –calls Thread.sleep() to display current image for set amount of time –calls repaint() to ensure next image is displayed

23 Algorithm animation Thread runs algorithm, updates display then sleeps After brief rest, wakes up again, runs to next point of interest in algorithm, updates display, sleeps again Sequence repeats until algorithm finishes

24 Example: Mergesort animation Uses MergeSorter class to sort random integer array MergeSorter.sort takes an array and a Comparator as arguments For demo, supply Sorter class that implements Runnable –run() method calls MergeSorter.sort() –Comparator supplied to sort() contains a calls to sleep() – pauses thread long enough to see progress of algorithm in display

25 Comparator - pseudocode Comparator comp = new Comparator() { public int compare (Object o1, Object o2) { draw array contents pause thread return ((Integer) o1).compareTo(o2); } };

26 Improvement – allow animation to pause until button is clicked Need to coordinate user interface thread & algorithm thread Use “gate” class to coordinate threads: –Step button opens gate, allows one operation through –Run button deactivates gate

27 Animation classes

28 Improved compare() method public int compare(Object o1, Object o2) { … if (gate.isActive()) gate.waitForOpen(); else Thread.sleep(DELAY); … return ((Integer) o1).compareTo(o2); }

29 Client/Server connections Port: location, designated by integer number, where information can be exchanged between client & server –Port values less than 1024 typically reserved for predefined services (ftp, telnet, , http, etc.) –User-defined ports use larger values

30 Client/Server connections Socket: combination of IP address & port –socket is where client “plugs in” to server, creating connection for flow of information –sockets also provide facilities for creating I/O streams

31 DateServer application Simple example of client/server interaction Establishes connection at client’s request Sends current data & time to client for output

32 Notes on DateServer Several methods (accept(), write() and ServerSocket()) can all throw an IOException; can simplify things by checking exceptions in the constructor interface, then handle in main(); exceptions thrown by library procedures pass up through constructor to calling procedure (main())

33 Notes on DateServer application Method accept() returns a Socket when the client makes a request The Socket is then used to create an output stream After making the connection, the server sends a message (this is the requested service) to the client

34 Notes on DateClient The client requests a socket to be created at given port on specific computer; in this example, we assume client & server are on same computer The IP address on which the application is running is accessed by method InetAddress.getLocalHost() A more general method would be: InetAddress.getByName(domainName), which takes the string representation (FQDN) and converts it into an IP address

35 Notes on DateClient Once created, a socket can be used to create an input stream, which can be converted to a BufferedReader, which provides a method (readLine()) for reading an entire line of input, which can then be printed out The DateServer/DateClient interaction is a simple example of a service provided to one client at a time, with one-way communication

36 Client/Server interaction with multiple clients Therapist class simulates a therapist, conducting a question/answer session with a client; works by the following rules: –answer any question with “Why do you want to know?” –answer any statement that begins with “I feel” with “Why do you feel that way?” –answer any statement that mentions a relative with “Tell me about your” name of relative –if none of the above apply, respond with “Tell me more”

37 TherapySession class In this program, several clients can be served simultaneously because each initial client request spawns a new Thread Actual service is provided via an instance of TherapySession, which gets both input and output streams passed to it - this permits 2-way communication between Client & Server

38 TherapySession class TherapySession extends Thread, so most of its action takes place in run(): –prints generic greeting –flush is used to transfer output across network, rather than let buffering process wait for more output –loop reads a line of text, then determines and writes response

39 TherapySession class Other methods include: –constructor: converts I/O streams to buffered reader and writer to simplify I/O processing –response method: implements rules for Therapist; returns appropriate String based on user input –isRelative: used to determine if a relative’s name appears in text

40 TherapyClient class Creates readers & writers to handle socket I/O Reads responses from stdin and passed to server, then writes replies to stdout