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

Similar documents
Multithreading Pearson Education, Inc. All rights reserved.

Multithreaded Programming

CS 556 Distributed Systems

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

7. MULTITHREDED PROGRAMMING

Multithreaded Programming

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

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

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

Threads Chate Patanothai

Processes and Threads. Industrial Programming. Processes and Threads (cont'd) Processes and Threads (cont'd)

Animation Part 2: MoveableShape interface & Multithreading

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Systems Programming & Scripting

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

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

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

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

Basics of. Multithreading in Java

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

Unit - IV Multi-Threading

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

Introduction to Java Threads

Software Practice 1 - Multithreading

Concurrent Programming using Threads

Multithreading using Java. Dr. Ferdin Joe John Joseph

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Programming Language Concepts: Lecture 11

Advanced Concepts of Programming

Java Threads. Introduction to Java Threads

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

JAVA - MULTITHREADING

What is a thread anyway?

Unit III Rupali Sherekar 2017

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

Amity School of Engineering

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

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

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

CS 159: Parallel Processing

Model Requirements and JAVA Programs MVP 2 1

Concurrency in Java Prof. Stephen A. Edwards

Exercise Session Week 8

Unit 5 - Exception Handling & Multithreaded

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

CIS233J Java Programming II. Threads

Concurrent Computing CSCI 201 Principles of Software Development

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

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

Concurrency - Topics. Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads

Exercise Session Week 8

Shared Objects & Mutual Exclusion

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

G52CON: Concepts of Concurrency

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

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

Shared-Memory and Multithread Programming

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

Concurrent Programming

Threads and Java Memory Model

CS 351 Design of Large Programs Threads and Concurrency

Techniques of Java Programming: Concurrent Programming in Java

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

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

Module - 4 Multi-Threaded Programming

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

Advanced Programming Concurrency

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

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

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

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

COE518 Lecture Notes Week 7 (Oct 17, 2011)

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

04-Java Multithreading

COMP30112: Concurrency Topics 4.1: Concurrency Patterns - Monitors

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

Object Oriented Programming. Week 10 Part 1 Threads

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

COMP346 Winter Tutorial 4 Synchronization Semaphores

Concurrency. Fundamentals of Computer Science

Threads in Java (Deitel & Deitel)

UNIT V CONCURRENT PROGRAMMING

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Object-Oriented Programming Concepts-15CS45

Multithread Computing

Chapter 19 Multithreading

Definition: A thread is a single sequential flow of control within a program.

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico.

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

CMSC 330: Organization of Programming Languages

MULTI-THREADING

Java Threads. COMP 585 Noteset #2 1

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

Problems with Concurrency. February 19, 2014

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

CS180 Review. Recitation Week 15

Parallel Programming Practice

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

Concurrent, Real-Time and Distributed Programming in Java

Transcription:

Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets 6-1 Copyright (c) 1999-2004 N. Afshartous

Chapter 6: Concurrency in Java After this chapter you will be able to: - Create threads - Incorporate synchronized methods - Put threads to sleep using wait - Wake up threads using notify 6-2 Copyright (c) 1999-2004 N. Afshartous

Creating Threads Two ways to create threads: - write a class which implements interface Runnable interface Runnable { public void run (); - or write a subclass of class Thread 6-3 Copyright (c) 1999-2004 N. Afshartous

Using Interface Runnable Method run will be called when a thread is started by calling Thread.start public class MyThread1 implements Runnable { private int id; public MyThread1 (int id) { this.id = id; public void run () { while (true) System.out.println("Message from #: " + id); Note: Implementing Runnable is the first way to incorporate threads 6-4 Copyright (c) 1999-2004 N. Afshartous

Creating MyThread1 Objects Class Thread has a constructor whose argument is of type Runnable class Thread { public Thread (Runnable target) {... Thread t1 = new Thread(new MyThread1(1)); Thread t2 = new Thread(new MyThread1(2)); t1.start(); t2.start(); Output Message from #1 Message from #2 Message from #1 Message from #2 6-5 Copyright (c) 1999-2004 N. Afshartous

Creating A Subclass of Thread Subclassing class Thread is the second way to incorporate threads public class MyThread2 extends Thread { private int id; public MyThread2 (int id) { this.id = id; public void run () { while (true) System.out.println("message from thread: " + id); 6-6 Copyright (c) 1999-2004 N. Afshartous

Creating MyThread2 Objects Thread t1 = new MyThread2(1); Thread t2 = new MyThread2(2); t1.start(); t2.start(); Output Message from #1 Message from #2 Message from #1 Message from #2... 6-7 Copyright (c) 1999-2004 N. Afshartous

Sleeping A thread may call the Thread.sleep method to sleep for a specified number of milliseconds public class MyThread2 extends Thread { private int id; public MyThread2 (int id) { this.id = id; public void run () { while (true) { System.out.println("message from thread: " + id); try { Thread.sleep(10); catch (InterruptedException e) { System.out.println("snooze was interrupted"); 6-8 Copyright (c) 1999-2004 N. Afshartous

InterruptedException The InterruptedException is thrown when the interrupt method of a Thread is called The interrupt method is defined in class Thread Thread t1 = new MyThread2(1); t1.start();... ti.interrupt(); // interrupt t1 s sleep 6-9 Copyright (c) 1999-2004 N. Afshartous

Synchronization Motivation: Example: to avoid race conditions a shared counter must properly synchronize increment operation Java solution: each object has an associated monitor Use keyword synchronized in method declaration Guarantee: only one thread may be executing any synchronized method of an object 6-10 Copyright (c) 1999-2004 N. Afshartous

Synchronized Methods Use keyword synchronized when necessary to avoid race conditions public class SharedCounter { private int counter = 0; public synchronized void increment () { counter ++; public synchronized void decrement () { counter --; Only one thread may be executing either method at one time 6-11 Copyright (c) 1999-2004 N. Afshartous

Waiting A thread may go to sleep by calling wait Example: A thread needs to wait until the counter is zero public class SharedCounter { private int counter = 0;... public void awaitzero () { if (counter!= 0) try { wait(); catch (InterruptedException e) { System.out.println( "wait was interrupted by another thread"); 6-12 Copyright (c) 1999-2004 N. Afshartous

Notifying Another thread may subsequently call notify/notifyall to wake up sleeping threads notify wakes up one of the sleeping threads notifyall wakes up all sleeping threads Note: since only one thread may be active inside a synchronized method, an awoken thread will not start executing immediately 6-13 Copyright (c) 1999-2004 N. Afshartous

Revised Increment/Decrement Use notifyall when counter becomes zero public class SharedCounter { private int counter = 0; public void awaitzero () {... public synchronized void increment () { counter ++; if (counter ==0) notifyall(); public synchronized void decrement () { counter --; if (counter == 0) notifyall(); 6-14 Copyright (c) 1999-2004 N. Afshartous

Thread Priorities Each thread has a priority which may be accessed via Thread.getPriority or changed by calling Thread.setPriority Threads with higher priorities are scheduled for execution more often Priorities are in the range: MIN_PRIORITY = 1 MAX_PRIORITY = 10 The garbage collector runs as a low priority thread 6-15 Copyright (c) 1999-2004 N. Afshartous

Changing Priority Call Thread.setPriority Thread t1 = new MyThread2(1); t1.setpriority(9); If new priority is not in the range MIN_PRIORITY to MAX_PRIORITY then IllegalArgumentException is thrown 6-16 Copyright (c) 1999-2004 N. Afshartous

Daemons Thread.setDaemon sets a thread to be either a user thread or a daemon thread Thread t1 = new MyThread2(1); t1.setdaemon(true); // must be done before // Thread is started Initially a thread is a user thread The java virtual machine exits when the only threads running are daemon threads 6-17 Copyright (c) 1999-2004 N. Afshartous

Thread Status Can call Thread.isAlive to determine the status of a thread Thread t1 = new MyThread2(1); if (!t1.isalive()) System.out.println("NOT alive"); t1.start(); if (t1.isalive()) System.out.println("alive"); t1.stop(); if (!t1.isalive()) System.out.println("NOT alive"); Thread.stop halts the execution of a thread Output NOT alive alive NOT alive 6-18 Copyright (c) 1999-2004 N. Afshartous

Class ThreadGroup Can group threads together using class ThreadGroup Class ThreadGroup defines methods that facilitate applying operations to all of the threads in the group 6-19 Copyright (c) 1999-2004 N. Afshartous

It s Exercise Time 6-20 Copyright (c) 1999-2004 N. Afshartous