Threads Chate Patanothai.

Slides:



Advertisements
Similar presentations
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Advertisements

Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads Just Java: C10–pages 251- C11–pages 275-
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
Multithreading.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
EE2E1. JAVA Programming Lecture 8 Multi-threading.
Java Programming: Advanced Topics
1 Java Threads and Synchronization Review Modified from slides taken from
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Threading Eriq Muhammad Adams J
Threads.
Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
1 5.0 Garbage collector & Threads : Overview Introduction: In this module we discuss the merits and demerits of automated garbage collection over manual.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Java 3: Odds & Ends Advanced Programming Techniques.
Multi-Threading in Java
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
CS203 Programming with Data Structures Introduction to Threads and Synchronization California State University, Los Angeles.
Distributed and Parallel Processing George Wells.
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Threads in Java Two ways to start a thread
Multithreading / Concurrency
Multi Threading.
Java Multithreading.
Multithreading.
Java Concurrency.
EE 422C Multithreading & Parallel Programming
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Java Concurrency.
Condition Variables and Producer/Consumer
Multithreading.
Condition Variables and Producer/Consumer
Java Threads אליהו חלסצ'י תכנות מתקדם תרגול מספר 6
Multithreading 2 Lec 24.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
برنامه‌نویسی چندنخی Multi-Thread Programming
Java Thread.
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threads Chate Patanothai

Objectives Define a thread Create separate threads Control the execution of a thread Communicate between threads Protect shared data C. Patanothai 31/8/2005 Threads

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

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 31/8/2005 Threads

Making a thread Making you class inherits from Thread simple cannot extend from other class Creating a new class that implements Runnable interface (preferred) better OOD single inheritance consistency Overriding run() method C. Patanothai 31/8/2005 Threads

Creating the thread create an instance of Runnable the Thread class already implemented Runnable interface C. Patanothai 31/8/2005 Threads

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

Implementing Runnable 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(); } class RunningClass [extends XXX] implements Runnable { public void run() { // must be overridden // code for thread execution C. Patanothai 31/8/2005 Threads

Starting the Thread Using the start method Placing the thread in runnable state C. Patanothai 31/8/2005 Threads

Basic Thread States Runnable Blocked Running New Dead blocking event unblocked scheduler start() run() completes C. Patanothai 31/8/2005 Threads

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 31/8/2005 Threads

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 void stopRunning() { done = true; public class ThreadController { private Runner r = new Runner(); private Thread t = new Thread(r); public void startThread() { t.start(); } public void stopThread() { t.stopRunning() C. Patanothai 31/8/2005 Threads

Basic Control of Threads Testing threads: isAlive() Accessing thread priority: getPriority() setPriority() Putting threads on hold: Thread.sleep() join() Thread.yield() C. Patanothai 31/8/2005 Threads

Thread Priority Thread.MIN_PRIORITY (1) Thread.NORM_PRIORITY (5) Thread.MAX_PRIORITY (10) C. Patanothai 31/8/2005 Threads

The join Method wait until the thread on which the join method is called terminates public static void main(String[] 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 31/8/2005 Threads

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 31/8/2005 Threads

Shared data one thread (A) pushing data onto 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]; one thread (A) pushing data onto the stack one thread (B) popping data off the stack 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 31/8/2005 Threads

The Object Lock Flag Every object has a “lock flag” use synchronized to enable interaction with this flag C. Patanothai 31/8/2005 Threads

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 31/8/2005 Threads

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 31/8/2005 Threads

Shared Data All access to shared data should be synchronized Shared data protected by synchronized should be private C. Patanothai 31/8/2005 Threads

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

Deadlock Two threads waiting for a lock from other no detection or avoidance by Java Can be avoided by the order to obtain locks applying the order throughout the program releasing the lock in the reverse order C. Patanothai 31/8/2005 Threads

Thread Interaction wait and notify 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 31/8/2005 Threads

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

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