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

Similar documents
Rubén Hidalgo/iStockphoto. CE 1 Calling await Without Calling. CE 2 Calling signalall Without Locking. ST 2 Object Locks and Synchronized

Check out ThreadsIntro project from SVN. Threads and Animation

Animation Part 2: MoveableShape interface & Multithreading

Threads Chate Patanothai

Concurrent Computing CSCI 201 Principles of Software Development

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

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

Object Oriented Programming. Week 10 Part 1 Threads

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

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

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

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

Multithreading Pearson Education, Inc. All rights reserved.

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

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

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

Advanced Concepts of Programming

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

Multithreaded Programming

Multi-threading in Java. Jeff HUANG

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

Produced by. Design Patterns. MSc in Communications Software. Eamonn de Leastar

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

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Advanced Programming Concurrency

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

Multithreading using Java. Dr. Ferdin Joe John Joseph

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

CS455: Introduction to Distributed Systems [Spring 2019] Dept. Of Computer Science, Colorado State University

Introduction to Java Threads

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

7. MULTITHREDED PROGRAMMING

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

CS 351 Design of Large Programs Threads and Concurrency

Program #3 - Airport Simulation


JAVA. Lab 12 & 13: Multithreading

Multithreading in Java Part 2 Thread - States JAVA9S.com

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

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

Produced by. Design Patterns. MSc in Communications Software. Eamonn de Leastar

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

Java Threads. COMP 585 Noteset #2 1

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

Synchronization synchronization.

Software Practice 1 - Multithreading

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

Threads Chapter 4. Reading: 4.1,4.4, 4.5

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

Java Threads. Introduction to Java Threads

CS360 Lecture 12 Multithreading

Produced by. Mobile Application Development. Higher Diploma in Science in Computer Science. Eamonn de Leastar

The Java Programming Language Basics. Identifiers, Keywords, and Types. Object-Oriented Programming. Objects and Classes. Exception Handling

CMSC 330: Organization of Programming Languages

Parallel Programming Practice

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

Exercise Session Week 8

Multithread Computing

public class Shared0 { private static int x = 0, y = 0;

Robotics and Autonomous Systems

JAVA - MULTITHREADING

Parallel Programming Practice

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

CharBuffer view of those bytes: This creates a view of the original ByteBuffer, which behaves like a. buffer as an int, you could do the following:

THREADS AND MULTITASKING ROBOTS

ROBOTICS AND AUTONOMOUS SYSTEMS

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

The Java Programming Language Basics. Identifiers, Keywords, and Types. Object-Oriented Programming. Objects and Classes. Exception Handling

Exercise Session Week 8

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

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

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

COMP30112: Concurrency Topics 4.1: Concurrency Patterns - Monitors

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

Multithreaded Programming

Unit - IV Multi-Threading

Part IV Other Systems: I Java Threads

Synchronization

G52CON: Concepts of Concurrency

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

Threads and Java Memory Model

Unit III Rupali Sherekar 2017

Overview of Java Threads (Part 2)

Exam Number/Code : 1Z Exam Name: Name: Java Standard Edition 6. Demo. Version : Programmer Certified Professional Exam.

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

CS360 Lecture 10 Multithreading

shared objects monitors run() Runnable start()

CSCD 330 Network Programming

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

Module - 4 Multi-Threaded Programming

Programming Language Concepts: Lecture 11

CS 556 Distributed Systems

Basics of. Multithreading in Java

COMP 213. Advanced Object-oriented Programming. Lecture 23. Shared Variables and Synchronization

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

CS193k, Stanford Handout #8. Threads 3

Lecture 03: Thread API (continue)

CSCD 330 Network Programming

Transcription:

Design Patterns MSc in Computer Science Produced by Eamonn de Leastar (edeleastar@wit.ie)! Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

Threads

Single-Threaded and Multithreaded Programs 28

The Lifecycle of a Thread Threads start running, pause, resume, and finally stop dynamically during program execution The states of all threads except the thread that the JVM is currently executing cannot change By default, the JVM tries to distribute control equally to all threads Threads with high priority values tend to preempt lower priority threads 29

State Transition Diagram of a Thread 30

Running a Thread Method 1 Steps: 1: Implement a class that derives from Thread class 2: Place the code for task into the run method of class public class MyThread extends Thread { public void run() { // Task statements go here... 31

Running a Thread 3. Create an object of class MyThread t = new MyThread(); 4. Call the start method to start the thread. t.start(); 32

Running a Thread Method 2 1: Implement a class that implements the Runnable interface!! public interface Runnable { void run(); 2: Place the code for task into the run method of class public class MyRunnable implements Runnable { public void run() { // Task statements go here... 33

Running a Thread 3. Create an object of class Runnable r = new MyRunnable(); 4. Construct a Thread object for the runnable object. Thread t = new Thread(r); 5. Call the start method to start the thread. t.start(); 34

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! 35

GreetingRunnable Outline public class GreetingRunnable implements Runnable { private String greeting;! public GreetingRunnable(String agreeting) { greeting = agreeting;! public void run() { // Task statements go here 36

Thread Action for GreetingRunnable 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(); 37

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

Running Threads sleep puts current thread to sleep for given number of milliseconds Thread.sleep(milliseconds) When a thread is interrupted, most common response is to terminate run 39

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

GreetingRunnable.java public class GreetingRunnable implements Runnable { private static final int REPETITIONS = 10; private static final int DELAY = 1000; private String greeting;! public GreetingRunnable(String agreeting) { greeting = agreeting;! public void run() { try { for (int i = 1; i <= REPETITIONS; i++) { Date now = new Date(); System.out.println(now + " " + greeting); Thread.sleep(DELAY); catch (InterruptedException exception) { 41

To Start the Thread Construct an object of your runnable class Runnable t = new GreetingRunnable("Hello World"); Then construct a thread and call the start method. Thread t = new Thread(r); t.start(); 42

GreetingThreadTester public class GreetingThreadTester { public static void main(string[] args) { GreetingRunnable r1 = new GreetingRunnable("Hello, World!"); GreetingRunnable r2 = new GreetingRunnable("Goodbye, World!"); Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); t1.start(); t2.start(); 43

Output Thu Dec 28 23:12:03 PST 2004 Hello, World! Thu Dec 28 23:12:03 PST 2004 Goodbye, 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:04 PST 2004 Goodbye, World! Thu Dec 28 23:12:05 PST 2004 Goodbye, World! Thu Dec 28 23:12:06 PST 2004 Hello, World! Thu Dec 28 23:12:06 PST 2004 Goodbye, World! Thu Dec 28 23:12:07 PST 2004 Hello, World! Thu Dec 28 23:12:07 PST 2004 Goodbye, World! Thu Dec 28 23:12:08 PST 2004 Hello, World! Thu Dec 28 23:12:08 PST 2004 Goodbye, World! Thu Dec 28 23:12:09 PST 2004 Hello, World! Thu Dec 28 23:12:09 PST 2004 Goodbye, World! Thu Dec 28 23:12:10 PST 2004 Hello, World! Thu Dec 28 23:12:10 PST 2004 Goodbye, World! Thu Dec 28 23:12:11 PST 2004 Goodbye, World! Thu Dec 28 23:12:11 PST 2004 Hello, World! Thu Dec 28 23:12:12 PST 2004 Goodbye, World! Thu Dec 28 23:12:12 PST 2004 Hello, World! 44

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 45

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 t.interrupt(); interrupt does not cause the thread to terminate it sets a boolean field in the thread data structure 2

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() { for (int i = 1; i <= REPETITIONS &&!Thread.interrupted(); i++) { Do work Clean up 3

Terminating Threads The sleep method throws an InterruptedException when a sleeping thread is interrupted Catch the exception public void run() { try { for (int i = 1; i <= REPETITIONS; i++) { Do work catch (InterruptedException exception) { Clean up Terminate the thread 4

Except where otherwise noted, this content is licensed under a Creative Commons Attribution-NonCommercial 3.0 License.! For more information, please see http:// creativecommons.org/licenses/by-nc/3.0/