22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.

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

Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
Threads Daniel Bennett, Jeffrey Dovalovsky, Dominic Gates.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread.
26-Jun-15 Threads and Turns. Thread review There are two ways to create a Thread object.. Extend Thread and supply a run method: class MyThread extends.
Slides prepared by Rose Williams, Binghamton University ICS201 Lectures 18 : Threads King Fahd University of Petroleum & Minerals College of Computer Science.
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.
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
29-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
50.003: Elements of Software Construction Week 5 Basics of Threads.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
Internet Software Development More stuff on Threads Paul Krause.
Java Programming: Advanced Topics
8-Oct-15 Threads and Multithreading. 2 Thread s A Thread is a single flow of control When you step through a program, you are following a Thread A Thread.
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)
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
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.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
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.
1 Web Based Programming Section 8 James King 12 August 2003.
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. Concurrent programming in Java How to make all things run-able?
Threading Eriq Muhammad Adams J
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
OPERATING SYSTEMS Frans Sanen.  Recap of threads in Java  Learn to think about synchronization problems in Java  Solve synchronization problems in.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Advanced Programming 2004, based on LY Stefanus’s slides slide 8.1 Multithreading : Thread Scheduling ThreadGroup.
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.
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.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
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 in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Threads and Multithreading. Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three general approaches:
CSC CSC 143 Threads. CSC Introducing Threads  A thread is a flow of control within a program  A piece of code that runs on its own. The.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
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.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Java Thread Programming
Multithreading / Concurrency
Multi Threading.
Java Multithreading.
Threads and Multithreading
CSE 501N Fall ‘09 21: Introduction to Multithreading
Chapter 19 Java Never Ends
Threads and Multithreading
Multithreading.
Threads and Multithreading
Multithreading.
Multithreaded Programming
Threads and Multithreading
Threads and Multithreading
Threads and Multithreading
Threads and Multithreading
Threads and Multithreading
Multithreading in java.
Threads and Multithreading
Threads and Multithreading
Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

22-Jun-15 Threads and Multithreading

2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three general approaches: Cooperative multiprocessing Preemptive multiprocessing Really having multiple processors

3 Multithreading Multithreading programs appear to do more than one thing at a time Same ideas as multiprocessing, but within a single program More efficient than multiprocessing Java tries to hide the underlying multiprocessing implementation

4 Why multithreading? Allows you to do more than one thing at once Play music on your computer’s CD player, Download several files in the background, while you are writing a letter Multithreading is essential for animation One thread does the animation Another thread responds to user inputs

5 Thread s A Thread is a single flow of control When you step through a program, you are following a Thread Your previous programs all had one Thread A Thread is an Object you can create and control

6 Sleeping Every program uses at least one Thread Thread.sleep(int milliseconds ); A millisecond is 1/1000 of a second try { Thread.sleep(1000); } catch (InterruptedException e) { } sleep only works for the current Thread

7 States of a Thread A Thread can be in one of four states: Ready: all set to run Running: actually doing something Waiting, or blocked: needs something Dead: will never do anything again State names vary across textbooks You have some control, but the Java scheduler has more

8 State transitions ready waiting runningdead start

9 Two ways of creating Thread s The easy way: Extend the Thread class: class Animation extends Thread {…} And override public void run() You can only extend one class, so if your class already extends some other class, you can’t do this The more general way: Implement the Runnable interface: class Animation implements Runnable {…} Override public void run( ) Create a new Thread with this class as a parameter Most of the time, you need to do things the second way

10 Extending Thread class Animation extends Thread { public void run( ) { code for this thread } Anything else you want in this class } Animation anim = new Animation( ); A newly created Thread is in the Ready state To start the anim Thread running, call anim.start( ); start( ) is a request to the scheduler to run the Thread --it may not happen right away The Thread should eventually enter the Running state

11 Implementing Runnable class Animation implements Runnable {…} The Runnable interface requires run( ) This is the “main” method of your new Thread Animation anim = new Animation( ); Thread myThread = new Thread(anim); To start the Thread running, call myThread.start( ); You do not write the start() method—it’s provided by Java As always, start( ) is a request to the scheduler to run the Thread --it may not happen right away

12 Starting a Thread Every Thread has a start( ) method Do not write or override start( ) You call start( ) to request a Thread to run The scheduler then (eventually) calls run( ) You must supply public void run( ) This is where you put the code that the Thread is going to run

13 Extending Thread : summary class Animation extends Thread { public void run( ) { while (okToRun) {... } } Animation anim = new Animation( ); anim.start( );

14 Implementing Runnable : summary class Animation extends Applet implements Runnable { public void run( ) { while (okToRun) {... } } Animation anim = new Animation( ); Thread myThread = new Thread(anim); myThread.start( );

15 Two kinds of Threads There are two kinds of Threads in Java: Nondaemon threads These are “independent” threads, which run until they reach a stopping point (for example, the end of your main method) Whenever you start a program, you get one nondaemon thread When you create a GUI, you get another nondaemon thread Daemon threads These are threads which die when all nondaemon threads finish The Java VM exits when only daemon threads are still running There are methods setDaemon(boolean) and boolean isDaemon() The System.exit(int) method kills all threads

16 Things a Thread can do Thread.sleep(milliseconds) yield( ) Thread me = currentThread( ); int myPriority = me.getPriority( ); me.setPriority(NORM_PRIORITY); if (otherThread.isAlive( )) { … } join(otherThread);

17 Animation requires two Thread s Suppose you set up Buttons and attach Listeners to those buttons... …then your code goes into a loop doing the animation… …who’s listening? Not this code; it’s busy doing the animation sleep( ms ) doesn’t help!

18 How to animate Create your buttons and attach listeners in your first (original) Thread Create a second Thread to run the animation Start the animation The original Thread is free to listen to the buttons However, Whenever you have a GUI, Java automatically creates a second (nondaemon) Thread for you You only have to do this yourself for more complex programs

19 Things a Thread should NOT do The Thread controls its own destiny Deprecated methods: myThread.stop( ) myThread.suspend( ) myThread.resume( ) Outside control turned out to be a Bad Idea Don’t do this!

20 How to stop another Thread Don’t use the deprecated methods! Instead, put a request where the other Thread can find it boolean okToRun = true; animation.start( ); public void run( ) { while (okToRun) {... main loop...}

21 How to pause another Thread Don’t use the deprecated methods! Instead, put a request where the other Thread can find it boolean paused = false; public void run( ) { while (okToRun) { while (paused) { try { Thread.sleep(100); } catch (InterruptedException e) { } }... main loop... } }

22 A problem What gets printed as the value of k ? This is a trivial example of what is, in general, a very difficult problem int k = 0; Thread #1: k = k + 1; Thread #2: System.out.print(k);

23 Tools for a solution You can synchronize an object: synchronized ( obj ) {...code that uses/modifies obj... } No other code can use or modify this object at the same time You can synchronize a method: synchronized void addOne( arg1, arg2,... ) { code } Only one synchronized method in a class can be used at a time (other methods can be used simultaneously) Synchronization is a tool, not a solution— multithreading is in general a very hard problem

24 wait(), notify(), notifyAll() A somewhat better, but more complex, alternative to sleeping and occasionally waking up to check whether to continue is to use wait() and either notify() or notifyAll() Like sleep, wait puts the current Thread into a waiting state Unlike sleep, wait allows the Thread to be “waked up” from outside notify() tells a particular Thread to wake up notifyAll() tells all Threads to wake up These methods can only be used within synchronized methods, and as a result are quite tricky to get right

25 The End