CSE 501N Fall ‘09 21: Introduction to Multithreading

Slides:



Advertisements
Similar presentations
1 Race Conditions When threads share access to a common object/data, they can conflict with each other and mess up the consistency of the object/data.
Advertisements

Locks (Java 1.5) Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until lock becomes available.
Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee.
Chapter 21 – Multithreading
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
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.
50.003: Elements of Software Construction Week 5 Basics of Threads.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
Chapter 21 – Multithreading Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Multithreading. Chapter Goals To understand how multiple threads can execute in parallel To learn how to implement threads To understand race conditions.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
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.
Next week (July 21) –No class –No office hour. Problem Multiple tasks for computer –Draw & display images on screen –Check keyboard & mouse input –Send.
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.
CSE 501N Fall ‘09 23: Advanced Multithreading: Synchronization and Thread-Safety December 1, 2009 Nick Leidenfrost.
Concurrent Programming and Threads Threads Blocking a User Interface.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
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.
Parallel Thinking with Java Multithreading. Introduction Algorithms which make use of more than one processor Very hot topic today because all chip manufacturers.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Lec 10 agenda >git fetch origin lab10g; > git checkout -b lab10g origin/lab10g; Format/rules for Week 11 Advanced Topics (all beyond the scope of this.
Chapter 23 Multithreading. Chapter Goals To understand how multiple threads can execute in parallel To learn how to implement threads To understand race.
Java Thread Programming
CSCD 330 Network Programming
Doing Several Things at Once
Threads in Java Two ways to start a thread
Multithreading / Concurrency
Chapter 22 – Multithreading
Java Multithreading.
Threads and Multithreading
Multithreaded Programming in Java
Multithreading Chapter 9.
More About Threads.
Multithreading in Java
Chapter 22 – Multithreading
ITEC324 Principle of CS III
Threads II IS
Threads and Multithreading
Multithreading.
Threads and Multithreading
Java Based Techhnology
Multithreading.
Multithreaded Programming
Threads and Multithreading
Threads and Multithreading
Threads and Multithreading
Threads and Multithreading
Threads and Multithreading
Threads and Multithreading
Threads and Multithreading
Threads and Multithreading
CSCD 330 Network Programming
Representation and Management of Data on the Internet
Threads.
Lecture 19 Threads CSE /6/2019.
Chapter 9 Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

CSE 501N Fall ‘09 21: Introduction to Multithreading 19 November 2009 Nick Leidenfrost

Lecture Outline Lab 8 questions? Threads Multithreading Race conditions

Threads A thread is a unit of execution in Java (and other languages…) Threads are executed independently of one another However, they may share resources (Objects in your program) Threads execute simultaneously* *The Java Virtual Machine executes each thread in the program for a short amount of time This gives the impression of parallel execution

Threads Programs we have written so far are Single-Threaded Java creates the Main Thread for us when we start our programs We will learn how to create additional threads “Multi-Threading” / Multi-Threaded Programs Exception in thread "main" java.lang.NullPointerException at OutOfBounds.doSomethingBad(OutOfBounds.java:25) at OutOfBounds.<init>(OutOfBounds.java:21) at OutOfBounds.main(OutOfBounds.java:10)

Why Use Multiple Threads? If we want to monitor something continuously Incoming Data More consistent user interaction We can execute statements and accept rich user input (key presses, mouse events) at the same time Our program doesn’t appear to stall if we start a resource intensive task Writing a large amount of data to a stream A large file to disk A large amount of data sent across the net Simultaneous Execution When multiple processors exist (with proper JVM) Simulated for single processor machines Like all design decisions, the choice to use multiple threads depends on your program goals

Creating Threads Threads can be created in one of two ways: By extending the java.lang.Thread class By implementing the java.lang.Runnable interface and passing our Runnable into a Thread

Running a Thread Implement a class that implements the Runnable interface public interface Runnable { void run(); }

Running a Thread Place the code for your task into the run method of your class public class MyRunnable implements Runnable { public void run () { // Task statements go here . . . } }

Running a Thread Create an object of your subclass Construct a Thread object from the Runnable object. Call the start method to start the thread. Runnable r = new MyRunnable(); Thread t = new Thread(r); t.start();

Starting a Thread To start a Thread, we MUST call it’s start() method We SHOULD NOT call run() directly Also, a thread is not started on creation start will create a new thread of execution and then call run() for us MyThread thread = new MyThread(); Thread.start(); //... More statements ... // Inside MyThread public void run () { while (!interrupted()) { // ... }

Starting a Thread If we just call run() on the new Thread, the current thread’s thread of execution will execute the statements in run MyThread thread = new MyThread(); Thread.run(); //... Not executed until ‘run’ // terminates ... // Inside MyThread public void run () { while (!interrupted()) { // ... }

Example A program to print a time stamp and "Hello World" once a second for ten seconds: Thu Dec 28 23:12:03 PST 2004 Hello, World! Thu Dec 28 23:12:04 PST 2004 Hello, World! Thu Dec 28 23:12:05 PST 2004 Hello, World! Thu Dec 28 23:12:06 PST 2004 Hello, World! Thu Dec 28 23:12:07 PST 2004 Hello, World! Thu Dec 28 23:12:08 PST 2004 Hello, World! Thu Dec 28 23:12:09 PST 2004 Hello, World! Thu Dec 28 23:12:10 PST 2004 Hello, World! Thu Dec 28 23:12:11 PST 2004 Hello, World! Thu Dec 28 23:12:12 PST 2004 Hello, World!

GreetingRunnable Outline public class GreetingRunnable implements Runnable { // Fields used by the task statements private String greeting; public GreetingRunnable(String aGreeting) { greeting = aGreeting; } public void run() { // Task statements go here . . . }

Thread Action for GreetingRunnable We want to: Print a time stamp Print the greeting Wait a second We can get the date and time by constructing a Date object Date now = new Date();

Thread Action for GreetingRunnable To wait a second, use the sleep method of the Thread class A sleeping thread can generate an InterruptedException Catch the exception Terminate the thread sleep(milliseconds)

Running Threads sleep puts current thread to sleep for given number of milliseconds When a thread is interrupted, most common response is to terminate run (We’ll come back to interruptions in a bit) Thread.sleep(milliseconds)

Generic run Method public void run() { try { // Task statements } catch (InterruptedException exception) { } // Clean up, if necessary }

GreetingRunnable.java // Code Example

Java Thread Scheduler The thread scheduler runs each thread for a short amount of time (a time slice) Then the scheduler activates another thread There will always be slight variations in running times especially when calling operating system services (e.g. input and output) There is no guarantee about the order in which threads are executed

Terminating Threads A thread terminates when its run method terminates Do not terminate a thread using the deprecated stop method Instead, notify a thread that it should terminate interrupt does not cause the thread to terminate–it sets a boolean field in the Thread data structure t.interrupt();

Terminating Threads The run method should check occasionally whether it has been interrupted Use the interrupted method An interrupted thread should release resources, clean up, and exit public void run() { int i = 0; while (i <= REPETITIONS && !Thread.interrupted()) { // Do work i++; } // Clean up }

Terminating Threads The sleep method throws an InterruptedException when a sleeping thread is interrupted Catch the exception Terminate the thread

Terminating Threads Java does not force a thread to terminate when it is interrupted It is entirely up to the thread what it does when it is interrupted Interrupting is a general mechanism for getting the thread's attention

Swing Event Thread When we open a window with Swing, Swing provides us a Thread to handle events You have been writing multi-threaded programs without knowing it! // Code example (Don’t worry about altering any of your Lab 8 code for thread interaction – we will do this in later labs)

Sample Application Create a BankAccount object Create two threads: t1 deposits $100 into the bank account for 10 iterations t2 withdraws $100 from the bank account for 10 iterations

Sample Application Monitor balance by modifying deposit and withdraw to print messages: // Code Example public void deposit(double amount) { System.out.print("Depositing " + amount); double newBalance = balance + amount; System.out.println(", new balance is " + newBalance); balance = newBalance; }

Sample Application Normally, the program output looks somewhat like this: The result should be zero when the program terminates, but sometimes it is not… Depositing 100.0, new balance is 100.0 Withdrawing 100.0, new balance is 0.0 Depositing 100.0, new balance is 100.0 Depositing 100.0, new balance is 200.0 Withdrawing 100.0, new balance is 100.0 . . . Withdrawing 100.0, new balance is 0.0

Sample Application Sometimes, you may notice messed-up output, like this: Depositing 100.0Withdrawing 100.0, new balance is 100.0, new balance is -100.0

Race Conditions When threads share common resources, they can conflict with each other Sample program: multiple threads manipulate a common BankAccount object

Race Conditions Here is the run method of DepositRunnable: … the WithdrawRunnable class is similar public void run() { try { for (int i = 1; i <= count; i++) { account.deposit(amount); Thread.sleep(DELAY); } } catch (InterruptedException exception) { } }

Scenario to explain Non-zero Result: Race Condition The first thread t1 executes the following lines The balance field is still 0, and the newBalance local variable is 100 t1 reaches the end of its time slice and thread t2 gains control System.out.print("Depositing " + amount); double newBalance = balance + amount;

Scenario to explain Non-zero Result: Race Condition t2 calls the withdraw method which withdraws $100 from the balance, making it -100 t2 goes to sleep T1 regains control and picks up where it left off – it executes: The balance is now 100 instead of 0 because the deposit method has the OLD value for balance System.out.println(", new balance is " + newBalance); balance = newBalance;

Corrupting the balance Field Thread 1 Thread 2 newBalance is 100, balance is still 0 System.out(“Depositing…”) newBalance = balance + amount; System.out(“Withdrawing...”) At this point, t1 reaches the end of its time slice newBalance = balance - amount; System.out(“The new balan...”) balance = newBalance; System.out(“The new balan...”) balance is set to -100 t2 goes to sleep, its time slice ends balance is set to 100, the value of newBalance balance = newBalance;

Race Condition Occurs if the effect of multiple threads on shared data depends on the order in which they are scheduled It is possible for a thread to reach the end of its time slice in the middle of a statement It may evaluate the right-hand side of an equation but not be able to store the result until its next turn

Race Condition Race condition can still occur: public void deposit(double amount) { balance = balance + amount; System.out.print("Depositing " + amount + ", new balance is " + balance); } Race condition can still occur: balance = the right-hand-side value

Conclusion Questions? Soon: Thread-safety Part 2 of Lab 8 is Online Lab Now