Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.

Slides:



Advertisements
Similar presentations
1 Multithreaded Programming in Java. 2 Agenda Introduction Thread Applications Defining Threads Java Threads and States Examples.
Advertisements

Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
1 Chapter 5 Threads 2 Contents  Overview  Benefits  User and Kernel Threads  Multithreading Models  Solaris 2 Threads  Java Threads.
Threads, SMP, and Microkernels Chapter 4. Process Resource ownership - process is allocated a virtual address space to hold the process image Scheduling/execution-
Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
1 Threads, SMP, and Microkernels Chapter 4. 2 Process: Some Info. Motivation for threads! Two fundamental aspects of a “process”: Resource ownership Scheduling.
Concurrency…leading up to writing a web crawler. Web crawlers.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Definitions Process – An executing program
1 Chapter 4 Threads Threads: Resource ownership and execution.
A. Frank - P. Weisberg Operating Systems Introduction to Tasks/Threads.
Threads Just Java: C10–pages 251- C11–pages 275-
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
1 Advanced Computer Programming Concurrency Multithreaded Programs Copyright © Texas Education Agency, 2013.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
9/13/20151 Threads ICS 240: Operating Systems –William Albritton Information and Computer Sciences Department at Leeward Community College –Original slides.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
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.
Java Threads Representation and Management of Data on the Internet.
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.
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
Next week (July 21) –No class –No office hour. Problem Multiple tasks for computer –Draw & display images on screen –Check keyboard & mouse input –Send.
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.
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?
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.
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 
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.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Multi-Threading in Java
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
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 & Synchronized Algoritma Pemrograman 3 Sistem Komputer – S1 Universitas Gunadarma 1.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
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.
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.
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.
CS203 Programming with Data Structures Introduction to Threads and Synchronization California State University, Los Angeles.
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multi Threading.
Java Multithreading.
Lecture 21 Concurrency Introduction
Threads Chate Patanothai.
Multithreaded Programming in Java
Threads, SMP, and Microkernels
Multithreading.
Java Based Techhnology
Multithreaded Programming
Lecture 4- Threads, SMP, and Microkernels
21 Threads.
Multithreading in java.
Representation and Management of Data on the Internet
Lecture 19 Threads CSE /6/2019.
CMSC 202 Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files to disk Perform useful computation (editor, browser, game) How does computer do everything at once? Multitasking Multiprocessing

Multitasking (Time-Sharing) Approach Computer does some work on a task Computer then quickly switch to next task Tasks managed by operating system (scheduler) Computer seems to work on tasks concurrently Can improve performance by reducing waiting

Multitasking Can Aid Performance Single task Two tasks

Multiprocessing (Multithreading) Approach Multiple processing units (multiprocessor) Computer works on several tasks in parallel Performance can be improved 4096 processor Cray X1 32 processor Pentium Xeon Dual-core AMD Athlon X2

Perform Multiple Tasks Using… 1. Process Definition – executable program loaded in memory Has own address space Variables & data structures (in memory) Each process may execute a different program Communicate via operating system, files, network May contain multiple threads

Perform Multiple Tasks Using… 2. Thread Definition – sequentially executed stream of instructions Shares address space with other threads Has own execution context Program counter, call stack (local variables) Communicate via shared access to data Multiple threads in process execute same program Also known as “lightweight process”

Motivation for Multithreading 1. Captures logical structure of problem May have concurrent interacting components Can handle each component using separate thread Simplifies programming for problem Example Web Server uses threads to handle … Multiple simultaneous web browser requests

Motivation for Multithreading 2. Better utilize hardware resources When a thread is delayed, compute other threads Given extra hardware, compute threads in parallel Reduce overall execution time Example Multiple simultaneous web browser requests… Handled faster by multiple web servers

Multithreading Overview Motivation & background Threads Creating Java threads Thread states Scheduling Synchronization Data races Locks Wait / Notify

Programming with Threads Concurrent programming Writing programs divided into independent tasks Tasks may be executed in parallel on multiprocessors Multithreading Executing program with multiple threads in parallel Special form of multiprocessing

Creating Threads in Java Two approaches Thread class public class Thread extends Object { … } Runnable interface public interface Runnable { public void run(); // work  thread }

Thread Class public class Thread extends Object implements Runnable { public Thread(); public Thread(String name); // Thread name public Thread(Runnable R); // Thread  R.run() public Thread(Runnable R, String name); public void run();// if no R, work for thread public void start();// begin thread execution... }

More Thread Class Methods public class Thread extends Object { … public static Thread currentThread() public String getName() public void interrupt() public boolean isAlive() public void join() public void setDaemon() public void setName() public void setPriority() public static void sleep() public static void yield() }

Creating Threads in Java 1. Thread class Extend Thread class and override the run method Example public class MyT extends Thread { public void run() { … // work for thread } MyT T = new MyT () ;// create thread T.start(); // begin running thread …// thread executing in parallel

Creating Threads in Java 2. Runnable interface Create object implementing Runnable interface Pass it to Thread object via Thread constructor Example public class MyT implements Runnable { public void run() { … // work for thread } Thread T = new Thread(new MyT); // create thread T.start(); // begin running thread …// thread executing in parallel

Creating Threads in Java Note Thread starts executing only if start() is called Runnable is interface So it can be multiply inherited Required for multithreading in applets

Threads – Thread States Java thread can be in one of these states New – thread allocated & waiting for start() Runnable – thread can begin execution Running – thread currently executing Blocked – thread waiting for event (I/O, etc.) Dead – thread finished Transitions between states caused by Invoking methods in class Thread new(), start(), yield(), sleep(), wait(), notify()… Other (external) events Scheduler, I/O, returning from run()…

Threads – Thread States State diagram runnable scheduler new dead runningblocked new start terminate IO, sleep, wait, join yield, time slice notify, notifyAll, IO complete, sleep expired, join complete

Daemon Threads Java threads types User Daemon Provide general services Typically never terminate Call setDaemon() before start() Program termination 1. All user threads finish 2. Daemon threads are terminated by JVM 3. Main program finishes

Threads – Scheduling Scheduler Determines which runnable threads to run Can be based on thread priority Part of OS or Java Virtual Machine (JVM) Scheduling policy Nonpreemptive (cooperative) scheduling Preemptive scheduling

Threads – Non-preemptive Scheduling Threads continue execution until Thread terminates Executes instruction causing wait (e.g., IO) Thread volunteering to stop (invoking yield or sleep)

Threads – Preemptive Scheduling Threads continue execution until Same reasons as non-preemptive scheduling Preempted by scheduler

Java Thread Example public class ThreadExample extends Thread { public void run() { for (int i = 0; i < 3; i++) { try { sleep((int)(Math.random() * 5000)); // 5 secs } catch (InterruptedException e) { } System.out.println(i); } public static void main(String[] args) { new ThreadExample().start(); System.out.println("Done"); }

Java Thread Example – Output Possible outputs 0,1,2,0,1,2,Done // thread 1, thread 2, main() 0,1,2,Done,0,1,2 // thread 1, main(), thread 2 Done,0,1,2,0,1,2 // main(), thread 1, thread 2 0,0,1,1,2,Done,2 // main() & threads interleaved thread 1: println 0, println 1, println 2 main (): thread 1, thread 2, println Done thread 2: println 0, println 1, println 2

Data Races public class DataRace extends Thread { static int x; public void run() { for (int i = 0; i < ; i++) { x = x + 1; x = x – 1; } public static void main(String[] args) { x = 0; for (int i = 0; i < ; i++) new DataRace().start(); System.out.println(x);// x not always 0! }

Thread Scheduling Observations Order thread is selected is indeterminate Depends on scheduler Thread can block indefinitely (starvation) If other threads always execute first Thread scheduling may cause data races Modifying same data from multiple threads Result depends on thread execution order Synchronization Control thread execution order Eliminate data races