Single processor CPU. Memory I/O

Similar documents
COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University

Lecture 10 Multithreading

Java FX. Threads, Workers and Tasks

CMSC 132: Object-Oriented Programming II. Threads in Java

Multithreading using Java. Dr. Ferdin Joe John Joseph

Threads Chate Patanothai

Multithread Computing

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

Module - 4 Multi-Threaded Programming

7. MULTITHREDED PROGRAMMING

Concurrent Computing CSCI 201 Principles of Software Development

COMP346 Winter Tutorial 4 Synchronization Semaphores

Programming Java. Multithreaded Programming

Introduction to Java Threads

Concurrency. Fundamentals of Computer Science

Michele Van Dyne MUS 204B Concurrency Issues

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova

Principles of Software Construction: Concurrency, Part 2

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Concurrency. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

Exercise Session Week 8

Problems with Concurrency. February 19, 2014

Synchronized Methods of Old Versions of Java

CMSC 132: Object-Oriented Programming II

Michele Van Dyne MUS 204B Threads

Threads. Fundamentals of Computer Science

Exercise Session Week 8

Animation Part 2: MoveableShape interface & Multithreading

Project. Threads. Plan for today. Before we begin. Thread. Thread. Minimum submission. Synchronization TSP. Thread synchronization. Any questions?

Midterm assessment - MAKEUP Fall 2010

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

Concurrent Programming: Threads. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Unit 5 - Exception Handling & Multithreaded


CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2015

CS193k, Stanford Handout #8. Threads 3

Principles of Software Construction: Concurrency, Part 1

CS193k, Stanford Handout #12. Threads 4 / RMI

Multithreading. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

Java Threads. COMP 585 Noteset #2 1

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

Lecture 5: Methods CS2301

CSCD 330 Network Programming

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation

F. Tip and M. Weintraub CONCURRENCY

Programming II (CS300)

2018/2/5 话费券企业客户接入文档 语雀

Chapter 32 Multithreading and Parallel Programming

Building a Java First-Person Shooter

Excep&ons and Threads

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

User Space Multithreading. Computer Science, University of Warwick

Programming II (CS300)

CSCD 330 Network Programming

Principles of Software Construction: Concurrency, Part 1

Handouts. 1 Handout for today! Recap. Homework #2 feedback. Last Time. What did you think? HW3a: ThreadBank. Today. Small assignment.

Multithreading Pearson Education, Inc. All rights reserved.

CMSC 330: Organization of Programming Languages

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

Multithreaded Programming

Threads, Concurrency, and Parallelism

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

Threads and Concurrency in Java

Part IV Other Systems: I Java Threads

Java s Implementation of Concurrency, and how to use it in our applications.

INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors.

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

public class MyThread extends Thread { try { private Shared theshared; threada.join(); threadb.join();

Java Threads. What Are Threads? General-purpose solution for managing concurrency. Multiple independent execution streams. Shared state.

Game Engineering: 2D

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Multiprocessing Threads/Lightweight objects Thread methods Concurrency Issues

JAVA. Lab 12 & 13: Multithreading

What is a Thread? Individual and separate unit of execution that is part of a process. multiple threads can work together to accomplish a common goal

Chapter 8 Threads Zindell Technologies, Ltd. Question 1: Which one statement below is true concerning the following code?

Concurrency CSCI 201 Principles of Software Development

Java Threads. Written by John Bell for CS 342, Spring 2018

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

JAVA - MULTITHREADING

JAVA Programming Language Homework VI: Threads & I/O

Process Characteristics. Threads Chapter 4. Process Characteristics. Multithreading vs. Single threading

Threads Chapter 4. Reading: 4.1,4.4, 4.5

CMPSCI 187: Programming With Data Structures. Lecture #20: Concurrency and a Case Study David Mix Barrington 24 October 2012

i219 Software Design Methodology 11. Software model checking Kazuhiro Ogata (JAIST) Outline of lecture

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Amity School of Engineering

System Programming. Practical Session 4: Threads and Concurrency / Safety

COP 4610: Introduction to Operating Systems (Spring 2015) Chapter 4: Threads. Zhi Wang Florida State University

CS 556 Distributed Systems

Lec 3. Compilers, Debugging, Hello World, and Variables

Chapter 19 Multithreading

GlobalLogic Technical Question Paper

Systems Fundamentals. SWE 622, Spring 2017 Distributed Software Engineering

COE518 Lecture Notes Week 7 (Oct 17, 2011)

Transcription:

Lec 17 Threads

Single processor CPU Memory I/O

Multi processes Eclipse PPT iclicker

Multi processor CPU CPU Memory I/O

Multi-core Core Core Core Core Processor Memory I/O

Logical Cores

Multi-threaded

Creating Threads 1. Write code for thread to execute public class Example implements Runnable { public void run() { // your code here 2. Create the thread and link to (1) Example ex = new Example(); Thread thread = new Thread(ex); 3. Start the thread thread.start();

What gets printed public class PrintChar implements Runnable { private char chartoprint; public PrintChar(char c) { chartoprint = c; A) Compiler error B) aaaaabbbbb C) bbbbbaaaaa D) Random combination of 5 a s and 5 b s public void run() { for(int i = 0; i < 5; i++) { System.out.print(charToPrint); public class Example { public static void main(string[] args) { Runnable a = new PrintChar('a ); Runnable b = new PrintChar('b'); Thread t1 = new Thread(a); Thread t2 = new Thread(b); t2.start(); t1.start();

main()

main() t2.start()

main() t2.start(); t1.start()

Creating Theads, pt II Create a class that extends Thread and implements run() public class Example extends Thread { public void run() { // your code here Start the thread Thread thread = new Example(); thread.start();

What gets printed public class Sum extends Thread { int start, stop, sum; public Sum(int start, int stop) { //initalize vars. public void run() { for(int i = start; i <= stop; i++) { sum += i; public class Example { private static final int SUM_NUMBERS = 5; public static void main(string[] args) { Thread t1 = new Sum(0, SUM_NUMBERS); t1.start(); System.out.println(((Sum) t1).sum); //note: this is ok! A) Compiler error B) 0 C) 15 D) Number between 0 and 15 E) B, C, or D Note: when we did this in class, it was Either B or C. D is possible, but very unlikely

thread.join Thread thread = new Sum(0, SUM_NUMBERS); thread.start(); try { thread.join(); catch (InterruptedException e) { e.printstacktrace();

How would you modify this to compute the answer faster public class Sum extends Thread { int start, stop, sum; public Sum(int start, int stop) { //initalize vars. public void run() { for(int i = start; i <= stop; i++) { sum += i; public class Example { private static final int SUM_NUMBERS = 5000000; public static void main(string[] args) { Thread t1 = new Sum(0, SUM_NUMBERS); t1.start(); try { t1.join(); catch (InterruptedException e) { e.printstacktrace(); System.out.println(((Sum) t1).sum); //note: this is ok!

HW1 HW3? Reasons to use threads Avoid blocking on background actions Should your GUI stop updating when waiting for, say, the hard drive to return a value? Two terrible examples: Your GPS not updating the screen while doing something else Windows Print manager locking down the whole system

Threading You get up for the morning and here are your tasks before you can leave the house: Brew coffee (takes 5 minutes) Pour coffee in to-go mug (1 minute) Get dressed (4 minutes) Make cereal (2 minutes) Eat cereal (5 minutes) Brush teeth (2 minutes) Turn on tablet to download podcast (3 minutes) How long did it take to get ready?

Events are threads! Each event handler is a thread helps with the User Experience (UX)

Can/should we parallelize or thread everything? Suppose you are playing a board game. Why make everyone take their turn in sequence? Can t everyone go at the same time?

class WithdrawHandlerClass implements EventHandler<ActionEvent> { @Override public void handle(actionevent e){ Runnable r = new WithdrawThread(); Thread t= new Thread(r); t.start(); try { t.join(); catch... b.settext("$ "+balance); if(balance < 20){ btnwithdraw.setdisable(true); class WithdrawThread implements Runnable{ public void run(){ int current_balance = balance; try{ Thread.sleep(1000); catch(exception exc) { System.out.println(exc); if(current_balance>=20){ current_balance-=20; balance = current_balance; System.out.println("Withdrew $20!"); What will happen when the user clicks the Withdraw $20 button twice? A. Nothing B. An error C. Java will print a message D. The balance variable will decrease to 0 E. The balance variable will decrease to negative 20

Synchronization How can we fix this? 1. Make sure only one thread is executing by making sure the method which operates on a shared variable is synchronized synchronized void deposit(int amount) 2. (Advanced) Use locks explicitly to ensure 1 thread in critical region Private static Lock lock = new ReentrantLock(); lock.lock(); // take the lock, then do something lock.unlock(); // release the lock

Synchronization Mr Homakov worked out that making two web browsers transfer money between the same cards, at the same time, sometimes duplicated the transfer and added funds to a gift card that had not been paid for.

Threading vs. Parallel Programming Threading Commonly refers to the scenario where you launch a thread to take care of something which may take a while Think coffee maker example (happens in the background) Parallel Programming Commonly refers to the scenario where you have more than one computing resource and are trying to divide up your task Think summing receipts example