Threads Just Java: C10–pages 251- C11–pages 275-

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

10. Multithreading 1 public class SumTest { public static void main(String a1[]) public static void main(String a1[]) { int a, b, sum; int a, b, sum; a.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Java Programming Transparency No. 1 Lecture 7. Java Threads Cheng-Chia Chen.
Tutorial 2 Adventures in Threading presented by: Antonio Maiorano Paul Di Marco.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Lecture 4 : JAVA Thread Programming
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
1 Java Threads and Synchronization Review Modified from slides taken from
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Online Appointment Book Implement a Client/Server application for an online appointment book. Client should be a Graphical User Interface application.
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.
Processes & Threads Bahareh Goodarzi. Single & Multiple Thread of control code files data code files data.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
CS884 (Prasad)java8Threads1 Concurrent Programming Multithreading.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
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.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 18 Advanced Java Concepts Threads and Multithreading.
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
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
Threading and Concurrency COM379T John Murray –
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.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Threads Eivind J. Nordby University of Karlstad Inst. for Information Technology Dept. of Computer Science.
Java 3: Odds & Ends Advanced Programming Techniques.
Multi-Threading in Java
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.
Peyman Dodangeh Sharif University of Technology Fall 2014.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
Java Threads Lilin Zhong. Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions 4. Concurrent access problems.
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.
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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
CS203 Programming with Data Structures Introduction to Threads and Synchronization California State University, Los Angeles.
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multithreading / Concurrency
Multithreading Lec 23.
Java Multithreading.
Multithreading.
Java Concurrency.
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Exception Handling Visit for more Learning Resources.
Java Concurrency.
Condition Variables and Producer/Consumer
Multithreading.
Condition Variables and Producer/Consumer
Java Based Techhnology
Multithreading.
13: Concurrency Definition:  A thread is a single sequential flow of control within a program. Some texts use the name lightweight process instead of thread.
برنامه‌نویسی چندنخی Multi-Thread Programming
21 Threads.
Computer Science 2 06A-Java Multithreading
Multithreading in java.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threads Just Java: C10–pages 251- C11–pages 275-

ThreadsSEA (WA)2 What is a Thread? A single thread of control/execution –the normal sequential execution Start Finish

ThreadsSEA (WA)3 Why would you want more? Need to do several things at the same time –Eg Java’s Garbage Collector Client/server Daemons Note: –Java is one of the few languages with threads

ThreadsSEA (WA)4 Unix Allows forking of new processes –ie multi-processing Start Finish

ThreadsSEA (WA)5 Multiple threads Forking is quite expensive Instead have lightweight processes AKA threads Several threads in a single program, “running” at the same time and, performing parts of the task.

ThreadsSEA (WA)6 Notice There is only one “program” or “process” The threads share that context Each thread has its own –Program counter –Stack –(and thread local storage—ThreadsLocal)

ThreadsSEA (WA)7 Option #1 Subclass the Thread class –Defined in java.lang package Override the run method

ThreadsSEA (WA)8 public class MyThread extends Thread { public MyThread(String str) { super(str); } public void run() { for (int i = 0; i < 5; i++) { System.out.println(getName() + " " + i ); try { sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) {} } System.out.println("End " + getName()); }

ThreadsSEA (WA)9 public class TestThreads { public static void main (String[] args) { new MyThread("A").start(); new MyThread("B").start(); } C:\lab4> javac MyThreads.java C:\lab4> java TestThreads

ThreadsSEA (WA)10 Option #2 Define a class that –implements the Runnable interface –from java.lang package Provide a definition of the run method Eg an Applet—already using extends extends JApplet implements Runnable Need to get a runnable object new Thread( new myRunnable() )

ThreadsSEA (WA)11 class MyRunnable implements Runnable { public void run() { System.out.println("MyRunnable is running"); try { sleep(1000); } catch (InterruptedException ie) { } } public static void main(String [] args) { Thread t = new Thread( new MyRunnable() ); t.start(); }

ThreadsSEA (WA)12 Whoops! This won’t compile Why? –It is not a subclass of Threads and so –Has no implementation of sleep (and also this means the exception is not thrown)

ThreadsSEA (WA)13 class MyRunnable implements Runnable { public void run() { System.out.println("MyRunnable is running"); try { sleep(1000); } catch (InterruptedException ie) { } } public static void main(String [] args) { Thread t = new Thread( new MyRunnable() ); t.start(); }

ThreadsSEA (WA)14 Need to get thread Thread t = Thread.currentThread(); This is a static (classic?) method in Threads Then you can say: try { t.sleep(1000); } catch (InterruptedException ie) { }

ThreadsSEA (WA)15 class MyRunnable2 implements Runnable { public void run() { System.out.println("MyRunnable2 is running"); Thread t = Thread.currentThread(); try { t.sleep(1000); } catch (InterruptedException ie) { } } public static void main(String [] args) { Thread t = new Thread( new MyRunnable2() ); t.start(); }

ThreadsSEA (WA)16 Thread life cycle Create a thread new MyThread("One") Starting a thread aThread.start() Creates system resources to run the thread Schedules the thread to be runnable Calls the thread's run method.

ThreadsSEA (WA)17 new running sleepingwaitingI/O blocked runnable yield End of quantum interrupt

ThreadsSEA (WA)18 Becoming runnable start() is called on the thread –and this then calls run() Time set for sleep ends Another object uses notify or notifyAll I/O completes

ThreadsSEA (WA)19 Becoming Not runnable Calls the sleep() method Calls the wait() method –for a specific condition to be satisfied Calls the yield() method Blocks on I/O

ThreadsSEA (WA)20 How do threads die? They just complete –Ends (falls through the }) –a return is executed –an Exception is thrown public void run() { int i = 0; while (i < 10) { System.out.println("i = " + i++); } }

ThreadsSEA (WA)21 Priority Threads have a priority from: lowest MIN_PRIORITY — 1 highest MAX_PRIORITY — 10 t1.setPriority( t1.getPriority() +1); Priority starts as the same as parent’s Higher priority threads pre-empt lower ones Equal priority—? –Depends on whether threads are time-sliced –Can also use yield()

ThreadsSEA (WA)22 Kinds of Threads Programming No interaction Threads work on part of the whole problem Act on shared data—mutual exclusion Communicating data –Producer-Consumer Daemons

ThreadsSEA (WA)23 Mutual exclusion Eg bank balance –Credit thread –Debit thread

ThreadsSEA (WA)24 Producer-Consumer producer consumer See pages 282- put() get()

ThreadsSEA (WA)25 #1—Locking methods() public class CP { private int [] circBuffer; … public synchronized int get() { … } public synchronized void put(int value) { … } // locked by Consumer // unlocked by Consumer // locked by Producer // unlocked by Producer

ThreadsSEA (WA)26 Note that this locks the object on which the method is acting That is: –Each object has an associated monitor This is an old idea from Prof. Hoare at Oxford

ThreadsSEA (WA)27 What if the buffer is empty? Consumer must wait try { // wait for Producer to put value wait(); } catch (InterruptedException e) { } … notify();// notify Producer return value; NB should be in a while (empty) { }

ThreadsSEA (WA)28 What if the buffer is full? Producer must wait try { // wait for Consumer to get value wait(); } catch (InterruptedException e) { } … notify();// notify Consumer NB should be in a while (full) { }

ThreadsSEA (WA)29 #2—locking a classic Method static synchronized void update() { All objects in that class would be controlled

ThreadsSEA (WA)30 #3—locking a block Need to lock the block on an object static Object lock = new Object() … synchronized (lock) { … block of statements }

ThreadsSEA (WA)31 Joining Threads public final void join() throws InterruptedException public final void join(long milliseconds) throws InterruptedException public final void join(long milliseconds, int nanoseconds) throws InterruptedException For example: t.join() waits for the Thread t to finish before continuing.

ThreadsSEA (WA)32 When does the app end? Java Virtual Machine continues until: System.exit(n) is called –and the security manager permits it. All threads (not daemon threads) have died –returning from the call to the run method –throwing an exception that propagates beyond the run method.