Threads Chate Patanothai

Similar documents
7. MULTITHREDED PROGRAMMING

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

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

Animation Part 2: MoveableShape interface & Multithreading

Advanced Concepts of Programming

Object Oriented Programming. Week 10 Part 1 Threads

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

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

Multithreading in Java Part 2 Thread - States JAVA9S.com

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

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

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

Unit - IV Multi-Threading

Module - 4 Multi-Threaded Programming

Multithreaded Programming

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

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

Introduction to Java Threads

Programming Language Concepts: Lecture 11

Chapter 32 Multithreading and Parallel Programming

Multithreaded Programming

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

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Multithread Computing

Multithreading using Java. Dr. Ferdin Joe John Joseph

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

Concurrent Programming using Threads

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

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

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

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

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

Concurrent Computing CSCI 201 Principles of Software Development

What is a thread anyway?

CS 556 Distributed Systems

CIS233J Java Programming II. Threads

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

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

Java Threads. Introduction to Java Threads

Threads in Java (Deitel & Deitel)

Software Practice 1 - Multithreading

CS 351 Design of Large Programs Threads and Concurrency

Chapter 19 Multithreading

G52CON: Concepts of Concurrency

CMSC 330: Organization of Programming Languages

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

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

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

Multi-threading in Java. Jeff HUANG

Problems with Concurrency. February 19, 2014

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

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


CS193k, Stanford Handout #8. Threads 3

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

COE518 Lecture Notes Week 7 (Oct 17, 2011)

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

Exercise Session Week 8

Unit III Rupali Sherekar 2017

Model Requirements and JAVA Programs MVP 2 1

Concurrent Programming

Exercise Session Week 8

CS360 Lecture 12 Multithreading

Java Threads. Thread. Rui Moreira. control within a program. threads. performed concurrently

Parallel Programming Practice

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

Java Threads. COMP 585 Noteset #2 1

CSCD 330 Network Programming

Parallel Programming Practice

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

CSCD 330 Network Programming

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

Lecture 9: Introduction to Monitors

CONCURRENT API AND PARALLEL PROGRAMMING

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

CMSC 132: Object-Oriented Programming II

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

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

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

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

CS 159: Parallel Processing

Program #3 - Airport Simulation

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

Performance Throughput Utilization of system resources

Concurrency and Java Programming

CS11 Java. Fall Lecture 7

Object-Oriented Programming Concepts-15CS45

Techniques of Java Programming: Concurrent Programming in Java

Threads, Concurrency, and Parallelism

04-Java Multithreading

MULTI-THREADING

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

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

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

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

Synchronization in Java

Threads. 3 Two-Minute Drill. Certification Objectives. Q&A Self Test. Start New Threads. Write Code That Uses wait(), notify(), or notifyall()

THREADS AND CONCURRENCY

MVP1: Introduction to concurrency in JAVA

Transcription:

Threads Chate Patanothai

Objectives Knowing thread: 3W1H Create separate threads Control the execution of a thread Communicate between threads Protect shared data C. Patanothai Threads 2

What are threads? An execution context a virtual it CPU the code for executing the data A process is a program in execution A process has one or more threads C. Patanothai Threads 3

Thread code and data In Java, the virtual CPU is encapsulated in an instance of the Thread class Two threads share the same code when they execute from instances of the same class Two threads share the same data when they share access to a common object C. Patanothai Threads 4

Making a thread New class extends Thread simple cannot extend from other class Creating a new class that t implements Runnable interface (preferred) better OOD single inheritance consistency Overriding run() method C. Patanothai Threads 5

Creating the thread create an instance of Runnable the Thread class already implemented Runnable interface C. Patanothai Threads 6

Starting the Thread Using the start method Placing the thread in runnable state C. Patanothai Threads 7

Subclass of Thread public class SomeThread extends Thread { public void run() { // code for thread execution public class ThreadTester { public static void main(string[] args) { // creating a thread SomeThread t = new SomeThread(); // start the thread t.start(); C. Patanothai Threads 8

Implementing Runnable public class RunningClass [extends XXX] implements Runnable { public void run() { // must be overridden // code for thread execution public class ThreadTester { public static void main(string[] args) { // creating an instance of a Runnable RunningClass rc = new RunningClass(); // creating a new thread for the Runnable instance Thread t = new Thread(rc); // starting the thread t.start(); C. Patanothai Threads 9

Basic Thread States Thread t = new Thread(); Thread t = new Thread(); t.start(); New Blocked Dead unblocked blocking event start() run() completes Runnable scheduler Running C. Patanothai Threads 10

Sleeping (ZZZZZZZZZZ) allow other threads a chance to execute sleep is a static method in the Thread class throws InterruptedException public class Runner implements Runnable { public void run() { while (true) { // do lots of interesting stuff : // Give other threads a chance try { Thread.sleep(10); // time in milliseconds catch (InterruptedException e) { // This thread s sleep was interrupted by another thread C. Patanothai Threads 11

Terminating a Thread when a thread completes, it cannot run again using a flag to indicate the exit condition public class Runner implements Runnable { private boolean done = false; public void run() { while (!done) {... public class ThreadController { private Runner r = new Runner(); private Thread t = new Thread(r); public void stoprunning() { done = true; public void startthread() { t.start(); t t() public void stopthread() { r.stoprunning() C. Patanothai Threads 12

Basic Control of Threads Testing threads: isalive() Accessing thread priority: getpriority() setpriority() Putting threads on hold: Thread.sleep() join() Thread.yield() C. Patanothai Threads 13

Thread Priority Thread.MIN_PRIORITY (1) Thread.NORM_PRIORITY (5) Thread.MAX_ PRIORITY (10) C. Patanothai Threads 14

The join Method wait until the thread on which the join method is called terminates public static ti void main(string[] i args) { Thread t = new Thread(new Runner()); t.start();... // do stuff in parallel... // wait for t to finish try { t.join(); catch (InterruptedException e) { // t came back early // continue this thread... C. Patanothai Threads 15

The Thread.yield Method give other runnable threads a chance to execute places the calling thread into the runnable pool if there are thread(s) in runnable, if not, yield does nothing sleep gives lower priority threads a chance yield gives other runnable threads a chance C. Patanothai Threads 16

Shared data bli l M St k { one thread (A) pushing data onto the stack one thread (B) popping data off the stack public class MyStack { int idx = 0; char[] data = new char[6]; public void push(char c) { data[idx] = c; idx++; public char pop() { idx--; return data[idx]; buffer p q idx = 2 A just finished push a character, then preempted buffer p q r idx = 2 B is now in Running ^ ^ C. Patanothai Threads 17

The Object Lock Flag Every object has a lock flag use synchronized to enable interaction with this flag C. Patanothai Threads 18

Using synchronized public class MyStack {... public void push(char c) { synchronized(this) { data[idx] = c; idx++;... public void push(char c) { synchronized(this) { data[idx] = c; idx++; C. Patanothai Threads 19

Releasing the Lock Flag A thread waiting for the lock flag of an object cannot resume running until it get the flag Released when the thread passes the end of the synchronized code block Automatically released when a break, return, or exception is thrown by the synchronized code block C. Patanothai Threads 20

Shared Data All access to shared data should be synchronized Shared data protected by synchronized should be private C. Patanothai Threads 21

Thread States (synchronized) New Blocked Dead unblocked blocking event start() run() completes Runnable scheduler Running acquires lock Blocked in object s lock pool synchronized C. Patanothai Threads 22

Deadlock Two threads waiting for a lock from other Thread A locks, and waits for Thread A locks, and waits for no detection or avoidance by Java Can be avoided by the order to obtain locks applying the order throughout h t the program releasing the lock in the reverse order C. Patanothai Threads 23

wait and notify Thread Interaction methods from java.lang.object if a thread issues a wait call on an object x, it pauses its execution until another thread issues a notify call on the same object x the thread MUST have the lock for that object (wait and notify are called only from within a synchronized block on the instance being called) C. Patanothai Threads 24

The pools Wait pool execute wait() Lock pool thread moved from synchronized wait pool notify() arbitrary thread notifyall() all threads Blocked in object s lock pool Running notify()or interrupt() wait() [must have lock]/ release lock Blocked in object s wait pool C. Patanothai Threads 25

Thread States (wait/notify) New Blocked Dead unblocked blocking event start() run() completes Runnable acquires lock scheduler Running synchronized wait() [must have lock]/ release lock Blocked in object s lock pool notify()or interrupt() t() Blocked in object s wait pool C. Patanothai Threads 26