CS360 Lecture 10 Multithreading

Similar documents
CS360 Lecture 12 Multithreading

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java

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

7. MULTITHREDED PROGRAMMING

Performance Throughput Utilization of system resources

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

Multithreading Pearson Education, Inc. All rights reserved.

Multithreading in Java Part 2 Thread - States JAVA9S.com

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright

User Space Multithreading. Computer Science, University of Warwick

Threads Chate Patanothai

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

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

Multithreaded Programming

Multithreaded Programming

G52CON: Concepts of Concurrency

cs Java: lecture #6

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

15CS45 : OBJECT ORIENTED CONCEPTS

Java Threads Instruct or: M Maina k Ch k Chaudh dh i ur ac.in in 1

Robotics and Autonomous Systems

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

THREADS AND MULTITASKING ROBOTS

ROBOTICS AND AUTONOMOUS SYSTEMS

Threads in Java (Deitel & Deitel)

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

By: Abhishek Khare (SVIM - INDORE M.P)

Contents. 6-1 Copyright (c) N. Afshartous

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

Threads Questions Important Questions

Producing Production Quality Software. Lecture 12: Concurrent and Distributed Programming Prof. Arthur P. Goldberg Fall, 2004

The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT

CS18000: Problem Solving And Object-Oriented Programming

COE518 Lecture Notes Week 7 (Oct 17, 2011)

CS18000: Programming I

Threads & Concurrency

Multithread Computing

CS 351 Design of Large Programs Threads and Concurrency

THREADS AND CONCURRENCY

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

Review what constitutes a thread Creating threads general Creating threads Java What happens if synchronization is not used? Assignment.

Threads, Concurrency, and Parallelism

Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

THREADS & CONCURRENCY

Object Oriented Programming. Week 10 Part 1 Threads

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Updates. Office B116E Office Hours : Friday 1 p.m. 2 p.m. Also by appointment Office Hours Purpose:

JAVA. Lab 12 & 13: Multithreading

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

Contents. G53SRP: Java Threads. Definition. Why we need it. A Simple Embedded System. Why we need it. Java Threads 24/09/2009 G53SRP 1 ADC

Handling Multithreading Approach Using Java Nikita Goel, Vijaya Laxmi, Ankur Saxena Amity University Sector-125, Noida UP India

Object Oriented Programming (II-Year CSE II-Sem-R09)

Animation Part 2: MoveableShape interface & Multithreading

Concurrent Computing CSCI 201 Principles of Software Development

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Deadlock. Only one process can use the resource at a time but once it s done it can give it back for use by another process.

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2)

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

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

Concurrent Programming using Threads

Unit - IV Multi-Threading

wait with priority An enhanced version of the wait operation accepts an optional priority argument:

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Objects as a programming concept

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

Generics Concurrency Exceptions (examples in C++, Java, & Ada)

Multi-threaded programming in Java

SRM INSTITUTE OF SCIENCE & TECHNOLOGY Faculty of Science and Humanities Department of Computer Science UNIT I - INTRODUCTION TO JAVA

Advanced Concepts of Programming

Threads & Concurrency

Lecture 35. Threads. Reading for next time: Big Java What is a Thread?

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

Threads and Parallelism in Java

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

What is a Thread? Why Multicore? What is a Thread? But a fast computer runs hot THREADS AND CONCURRENCY. Concurrency (aka Multitasking)

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Threads(in Java) CSC J Paul Gibson, D311.

CS 556 Distributed Systems

JAVA - MULTITHREADING

THREADS & CONCURRENCY

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

Introduction to Java Threads

Threads Assistant Professor DCS Operating System Concepts

CMSC 132: Object-Oriented Programming II

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Programming Language Concepts: Lecture 11

Multithreading using Java. Dr. Ferdin Joe John Joseph

Ch 9: Control flow. Sequencers. Jumps. Jumps

Java for Non Majors Spring 2018

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

CSCD 330 Network Programming

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

UE 2I002 (ex LI230) : éléments de programmation par objets avec Java TD10 - Exceptions

CSCD 330 Network Programming

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

Techniques of Java Programming: Concurrent Programming in Java

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

Transcription:

Tuesday, March 9, 2004 Reading Exception Handling: Chapter 15 Multithreading: Chapter 16 CS360 Lecture 10 Multithreading Declaring New Exception Types Most programmers use existing exception classes from the Java API or from the third party vendors. If you do need to create an exception class, then you should extend the class Exception and specify two constructors. public class MyException extends Exception public MyException() public MyException(String reason) super(reason); public class NonZero public NonZero(int number) throws MyException if( number == 0 ) throw new MyException( "The argument was zero"); System.out.println("Number " + number

+ " is non zero"); public static void main(string[] args) try NonZero nz1 = new NonZero(1); NonZero nz0 = new NonZero(0); System.out.println("All OK"); catch( MyException e ) System.out.println(e); Multithreading Performing operations concurrently on computers means that we can perform two operations at the same time. Question: Can computers execute operations concurrently? Historically, concurrency has been implemented as operating-system primitives available only to experienced system programmers. Then Ada came along. It supported concurrency primitives. Java makes concurrency primitives available to application programmers. Applications contain threads of execution, where each thread designates a portion of a program that may execute concurrently with other threads. Question: When would an application need to use multithreading? Threading mechanisms in various operating systems handle thread scheduling differently. Issues with Concurrent Programming Writing concurrent programs presents issues that do not occur when writing sequential code:

- Safety: Two different threads could write to the same memory location at the same time leaving the memory location in an improper state - Liveness: Threads can become deadlocked, each thread waiting forever for the other to perform a task. - Nondeterminism: Thread activities can become intertwined. This can make the program harder to debug. - Communication: Different threads in the same program execute autonomously from each other. Communication between threads is an issue. States of a Thread Start, run, etc. Example public class ExtendingThreadExample extends Thread for( int count = 0; count < 4; count ++ ) System.out.println( "Message " + count + " From: Mum" ); ExtendingThreadExample parallel = new ExtendingThreadExample(); System.out.println( "Create the thread" ); parallel.start(); System.out.println( "Started the thread" ); System.out.println( "End" );

Output Create the thread Started the thread End Message 0 From: Mum Message 1 From: Mum Message 2 From: Mum Message 3 From: Mum Output Create the thread Message 0 From: Mum Message 1 From: Mum Message 2 From: Mum Message 3 From: Mum Started the thread End Giving a Thread a Name Each thread can be given its own name, which can be useful. public class ExtendingThreadExample extends Thread public ExtendingThreadExample( String name ) super( name ); for( int count = 0; count < 4; count ++ ) System.out.println( "Message " + count + " From: " + Thread.currentThread().getName() );

ExtendingThreadExample parallel = new ExtendingThreadExample( "Dad" ); System.out.println( "Create the thread" ); parallel.start(); System.out.println( "Started the thread" ); System.out.println( "End" ); The next example shows a simple thread that we will be using throughout the lecture. public class SimpleThread extends Thread private int maxcount = 32; public SimpleThread( String name ) super( name ); public SimpleThread( String name, int repetitions ) super( name ); maxcount = repetitions; public SimpleThread( int repetitions ) maxcount = repetitions; for( int count = 0; count < maxcount; count++ ) System.out.println( count + " From: " + getname() );

The following example uses the SimpleThread class. The output depends on whether a multiprocessor or single processor machine is used to run the program. public class RunSimpleThread SimpleThread first = new SimpleThread( 5 ); SimpleThread second = new SimpleThread( 5 ); first.start(); System.out.println( "Started " + first.getname() ); second.start(); System.out.println( "Started " + second.getname() ); System.out.println( "End" ); Output 0 From: Thread-1 1 From: Thread-1 2 From: Thread-1 3 From: Thread-1 4 From: Thread-1 Started Thread-1 0 From: Thread-2 1 From: Thread-2 2 From: Thread-2 3 From: Thread-2 4 From: Thread-2 Started Thread-2 End Thread Priority Each thread has a priority. If there are two or more active threads and one has a higher priority than others, the higher priority thread is run until it is done or not active. java.lang.thread field Value Thread.MAX_PRIORITY 10

Thread.NORM_PRIORITY 5 Thread.MIN_PRIORITY 1 How to Determine Priorities Continuously running parts of the program should have lower priority than rarer events. User inputs should have very high priority. A thread that continually updates some data should have the lowest priority. public class PriorityExample SimpleThread first = new SimpleThread( 5 ); SimpleThread second = new SimpleThread( 5 ); second.setpriority( 10 ); first.setpriority( 1 ); first.start(); second.start(); System.out.println( "End" ); 0 From: Thread-2 1 From: Thread-2 2 From: Thread-2 3 From: Thread-2 4 From: Thread-2 End 0 From: Thread-1 1 From: Thread-1 2 From: Thread-1 3 From: Thread-1 4 From: Thread-1 Threads only run once. Once a thread has been run it can t be restarted.

Thread Scheduling Time-slicing A thread is run for a short time slice and suspended. It resumes only when it gets its next turn. Threads of the same priority share turns. Non time-sliced Threads run until: - they end - they are terminated - they are interrupted, higher priority threads interrupts lower priority threads - they go to sleep - they block on some call - they yield Java does not specify if threads are time-sliced or not. Implementations are free to decide. public class InfinityThread extends Thread while( true ) System.out.println( "From: " + getname() ); InfinityThread first = new InfinityThread(); InfinityThread second = new InfinityThread(); first.start(); second.start(); What do you think is output?

Types of Threads Several of the examples shown continue running even after the main method has completed running. The reason for this is because they are user threads. In Java there are two types of threads: - Daemon threads are expendable. When all the user threads have completed, the program ends and all daemon threads are stopped - User threads are not expendable. They continue to execute until their run method ends or an exception propagates beyond the run method. public class DaemonExample extends Thread DaemonExample shortlived = new DaemonExample(); shortlived.setdaemon( true ); shortlived.start(); System.out.println( "Bye" ); while( true ) System.out.println( "From: " + getname() ); System.out.flush();