Java Thread Programming

Slides:



Advertisements
Similar presentations
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Advertisements

Multithreading The objectives of this chapter are:
Thread Control methods The thread class contains the methods for controlling threads Thread() create default thread Thread(target: runnable ) creates new.
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.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
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: Advanced Topics
Java Programming, Second Edition Chapter Seventeen Multithreading and Animation.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
Multithreading in Java Project of COCS 513 By Wei Li December, 2000.
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.
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. Concurrent programming in Java How to make all things run-able?
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.
Advanced Programming 2004, based on LY Stefanus’s slides slide 8.1 Multithreading : Thread Scheduling ThreadGroup.
Java Thread and Memory Model
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.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
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.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
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.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
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.
Multithreading The objectives of this chapter are:
Doing Several Things at Once
Multithreading / Concurrency
Chapter 13: Multithreading
Multi Threading.
Java Multithreading.
Multithreading.
Threads and Multithreading
Multithreaded Programming in Java
Lecture 21 Concurrency Introduction
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreading Chapter 23.
Threads and Multithreading
Multithreading.
Synchronization Issues
Threads and Multithreading
Java Based Techhnology
Multithreading.
Multithreaded Programming
Threads and Multithreading
Threads and Multithreading
21 Threads.
Threads and Multithreading
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Threads and Multithreading
Threads and Multithreading
Multithreading in java.
Threads and Multithreading
Threads and Multithreading
Threads and Multithreading
Threads.
Multithreading The objectives of this chapter are:
CMSC 202 Threads.
More concurrency issues
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Java Thread Programming Paul Hyde

Purpose Review what we’ve learned Add details

Java Threads display GUI JVM event handler main garbage collection Allows better user interaction (e.g., don’t wait for graphics to load), simulation of simultaneous activities (e.g., edit & print document), other activities while waiting for I/O garbage collection Second thread always running in JVM http://www.ibm.com/developerworks/library/j-thread.html When you are writing graphical programs that use AWT or Swing, multithreading is a necessity for all but the most trivial programs.

Thread costs Memory resources. Each thread has two execution call stacks. Processor overhead required for context switch. Work to start, stop and destroy a thread. Consideration for brief background tasks (e.g., checking for new email).

Java & Threads Important feature built into core of language Thread and ThreadGroup classes in java.lang package Object has wait() and notify() methods for inter-thread communication synchronized keyword used to control concurrent access to data garbage collection frees developer from knowing when memory for an object can be released.

Simple Thread example Steps to spawn a new thread: Extend java.lang.Thread class Override run() method in subclass Create instance of new class Invoke start() method on instance NOTE: implementing Runnable often works better in real applications, but extending Thread is a simple way to get started with multi-threading.

<<interface>> Example continued public class TwoThreads extends Thread { …. } <<interface>> Runnable Object Thread TwoThreads

Example continued public class TwoThreads extends Thread { public void run() { for (int i=0; i<10; ++i) System.out.println(“running”); } // elsewhere, e.g., in main TwoThreads tt = new TwoThreads(); tt.start(); somethingElse(); // invokes run of TwoThread as soon as thread scheduler // can get to it, may be before or after somethingElse // Order of statement execution between two threads is // indeterminate – dangerous if specific order is needed // for correctness!

currentThread In some programs it’s possible for more than one Thread to execute the same method. The currentThread() method can be used to access the currently executing thread.

start & isAlive start() means thread is ready, run() method should be executed at earliest convenience isAlive() determines whether thread has been started and is still running

sleep example A thread cannot put another thread to sleep A sleeping thread can be interrupted (another thread calls interrupt), so must catch InterruptedException Better than a “busy loop” because it doesn’t use processor cycles

Gracefully stopping Threads (chapter 5) Threads die a natural death when run() method ends e.g., (for int i=0; i<10; i++) { …. } // run() ends But thread run methods often contain an infinite loop May need to pause a thread, e.g., if executing a lengthy operation May need to terminate the thread stop() has been deprecated because it can lead to corrupted data. Releases locks, which may leave data in invalid state. – so what to do?

Alternative to stop() include a volatile boolean stopRequested in thread class set stopRequested to false at beginning of run() while loop in run() checks status of stopRequested provide method to set stopRequested to true when appropriate

volatile* for efficiency, default is to reconcile shared values when thread enters or leaves a synchronized block of code. Default is good when only one thread interacts with member variables of an object; can be a problem if two threads interact. volatile forces threads to reread the variable’s value from memory every time threads must write values back to shared memory as soon as they occur (no caching) Use volatile on member variables that can be accessed by two or more threads unless all threads access the variables within synchronized blocks. * not emphasized, you may encounter it

More on volatile http://www.ibm.com/developerworks/library/j-thread/index.html The volatile keyword was introduced to the language as a way around optimizing compilers. Take the following code for example: class VolatileTest { boolean flag; public void foo() { flag = false; if(flag) { //this could happen } } } An optimizing compiler might decide that the body of the if statement would never execute, and not even compile the code. If this class were accessed by multiple threads, flag could be set by another thread after it has been set in the previous code, but before it is tested in the if statement. Declaring variables with the volatile keyword tells the compiler not to optimize out sections of code by predicting the value of the variable at compile time.

synchronized ensures that only one thread is allowed inside a method at one time. Can also synchronize blocks Collections are not inherently thread safe (decision based on performance).