Programming Java. Multithreaded Programming

Similar documents
Module - 4 Multi-Threaded Programming

Object Oriented Programming. Week 10 Part 1 Threads


Software Practice 1 - Multithreading

Concurrent Programming using Threads

CMSC 132: Object-Oriented Programming II. Threads in Java

Unit - IV Multi-Threading

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

COE518 Lecture Notes Week 7 (Oct 17, 2011)

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

7. MULTITHREDED PROGRAMMING

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Multi-threading in Java. Jeff HUANG

Synchronized Methods of Old Versions of Java

Amity School of Engineering

Unit 5 - Exception Handling & Multithreaded

Object-Oriented Programming Concepts-15CS45

Introduction to Java Threads

Object Oriented Programming (II-Year CSE II-Sem-R09)

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

Threads Chate Patanothai

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

Multithread Computing

Multithreaded Programming

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

04-Java Multithreading

JAVA - MULTITHREADING

Java Threads. COMP 585 Noteset #2 1

COMP346 Winter Tutorial 4 Synchronization Semaphores

Chapter 8 Threads Zindell Technologies, Ltd. Question 1: Which one statement below is true concerning the following code?

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

Techniques of Java Programming: Concurrent Programming in Java

Java Threads. Introduction to Java Threads

CMSC 132: Object-Oriented Programming II

Program #3 - Airport Simulation

Thread Programming 1

What is a thread anyway?

Multithreading using Java. Dr. Ferdin Joe John Joseph

Animation Part 2: MoveableShape interface & Multithreading

Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Contents. G53SRP: Java Threads. Definition. Why we need it. A Simple Embedded System. Why we need it. Java Threads 24/09/2009 G53SRP 1 ADC

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

Chapter 19 Multithreading

MULTI-THREADING

Single processor CPU. Memory I/O

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2)

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Part IV Other Systems: I Java Threads

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

Multithreading. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

JAVA. Lab 12 & 13: Multithreading

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci

public class Shared0 { private static int x = 0, y = 0;

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

Advanced Concepts of Programming

Dining philosophers (cont)

Synchronization synchronization.

Multithreaded Programming

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Basics of. Multithreading in Java

Definition: A thread is a single sequential flow of control within a program.

Programming Language Concepts: Lecture 11

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17

EDA095 Processes and Threads

By: Abhishek Khare (SVIM - INDORE M.P)

Unit III Rupali Sherekar 2017

EDAF65 Processes and Threads

Threads, Concurrency, and Parallelism

Concurrency with Threads and Actors

Component-Based Software Engineering

EDA095 Processes and Threads

Threads in Java (Deitel & Deitel)

MVP1: Introduction to concurrency in JAVA

CSCD 330 Network Programming

The Java Programming Language Basics. Identifiers, Keywords, and Types. Object-Oriented Programming. Objects and Classes. Exception Handling

CMSC 330: Organization of Programming Languages

CS 351 Design of Large Programs Threads and Concurrency

Performance Throughput Utilization of system resources

Principles of Software Construction: Concurrency, Part 2

CS193k, Stanford Handout #8. Threads 3

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

CERTIFICATION OBJECTIVES

Chapter 32 Multithreading and Parallel Programming

COMP30112: Concurrency Topics 4.1: Concurrency Patterns - Monitors

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

Time-Sharing Operating Systems. EDA095 Processes and Threads. Process Creation. The Content of a Process

Threads & Timers. CSE260, Computer Science B: Honors Stony Brook University

CSCD 330 Network Programming

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Parallel Programming Practice

Synchronization in Concurrent Programming. Amit Gupta

Overview of Java Threads (Part 2)

Threads(in Java) CSC J Paul Gibson, D311.

Parallel Programming Practice

The Java Programming Language Basics. Identifiers, Keywords, and Types. Object-Oriented Programming. Objects and Classes. Exception Handling

Transcription:

Programming Multithreaded Programming Incheon Paik 1 Contents An Overview of Threads Creating Threads Synchronization Deadlock Thread Communication 2

An Overview of Threads What is a Thread? A sequence of execution within a process A Lightweight process JVM manages and schedules threads Possible States: (1) new (2) ready (3) running (4) waiting (5) dead 3 An Overview of Threads Thread life cycle Dead Sleep,wait,I/O New Ready Running Waiting 4

Creating Threads Extending Thread Class class ThreadX extends Thread { // process Threads class RunnableY implements Runnable { // process Threads Runnable Interface Starting a Thread ThreadX tx = new ThreadX(); tx.start(); Starting a Thread RunnableY ry = new RunnableY(); Thread ty = new Thread(ry); tx.start(); run() method public void run(); Thread Constructor Thread() Thread(Runnable r) Thread(Runnable r, string s) Thread(String s) 5 Methods in a Thread Static Methods of the Thread Class static Tread currentthread() static void sleep(long msec) throws int erruptedexception static void sleep(long msec, int nsec) t hrows InterruptedException static void yield() Refer to the URL http://java.sun.com/j2se/1.4.2/ docs/api/java/lang/thread.html Instance Methods of Thread String getname() int getpriority() boolean isalive() void join() throws InterrupteException void join(long msec) throws Interrupte dexception void join(long msec, int nsec) throws I nterruptedexception void run() void setname(string s) void setpriority(int p) void start() String tostring() 6

Creating Threads class ThreadX extends Thread { while(true) { Thread.sleep(2000); System.out.println("Hello"); catch(interruptedexception ex) { ex.printstacktrace(); Result : Hello 2 seconds Hello Body of run method class ThreadDemo1 { public static void main(string args[]) { ThreadX tx = new ThreadX(); tx.start(); 7 Creating Threads class ThreadM extends Thread { for (int i = 0; i < 10; i++) { Thread.sleep(1000); System.out.println("ThreadM"); catch (InterruptedException ex) { ex.printstacktrace(); class ThreadN extends Thread { for (int i = 0; i < 20; i++) { Thread.sleep(2000); System.out.println("ThreadN"); catch(interruptedexception ex) { ex.printstacktrace(); class JoinDemo1 { public static void main(string args[]) { 8 ThreadM tm = new ThreadM(); tm.start(); ThreadN tn = new ThreadN(); tn.start(); tm.join(); tn.join(); join() method: Waits for this thread to die. System.out.println("Both threads have finished"); catch (Exception e) { e.printstacktrace();

Synchronization Thread Scheduling Synchronized Block Synchronized (obj) { // Process Block If a thread invokes a synchronized method, the object will be locked. If other threads invoke the synchronized method of that object, the threads will be blocked. Data Corruption! Need Synchronization 9 Locking Objects with Synchronized Methods thread 1 run() { obj1.method2(); thread 2 run() { obj1.method3(); obj1.method1(); obj2.method1(); thread 3 run() { obj2.method3(); obj2.method2(); 1 OK. method2() Not busy obj 1 synchronized method1() synchronized method2() method3() 2 3 Always OK. 4 5 OK. 6 method1() Not busy obj 2 No! Not while method2() for obj1 is executing 10 No! Not while method1() for obj2 is executing synchronized method1() synchronized method2() method3() Always OK.

Synchronization class Account { private int balance = 0; synchronized void deposit(int amount) { balance += amount; int getbalance() { return balance; class Customer extends Thread { Account account; Customer(Account account) { this.account = account; for (int i = 0; i < 100000; i++) { account.deposit(10); catch(exception e) { Result : e.printstacktrace(); 10,000,000 class BankDemo { private final static int NUMCUSTOMERS = 10; 11 public static void main(string args[]) { // Create Account Account account = new Account(); //Create and start customer threads Customer customers[] = new Customer[NUMCUSTOMERS]; for (int i = 0; i < NUMCUSTOMERS; i++) { customers[i] = new Customer(account); customers[i].start(); //Wait for customer threads to complete for (int i = 0; i < NUMCUSTOMERS; i++) { customers[i].join(); catch(interruptedexception e) { e.printstacktrace(); // Display Account balance System.out.println(account.getBalance()); Deadlock class A { B b; synchronized void a1() { System.out.println("Starting a1"); b.b2(); synchronized void a2() { System.out.println("Starting a2"); class B { A a; synchronized void b1() { System.out.println("Starting b1"); a.a2(); synchronized void b2() { System.out.println("Starting b2"); class Thread1 extends Thread { A a; Thread1(A a) { this.a = a; for (int i = 0; i < 100000; i++) a.a1(); class Thread2 extends Thread { B b; Thread2(B b) { this.b = b; for (int i = 0; i < 100000; i++) b.b1(); class DeadlockDemo { public static void main(string args[]) { // Create Objects A a = new A(); B b = new B(); a.b = b; b.a = a; 12 // Create threads Thread1 t1 = new Thread1(a); Thread2 t2 = new Thread2(b); t1.start(); t2.start(); // Wait for threads to complete t1.join(); t2.join(); catch(exception e) { e.printstacktrace(); //Display Message System.out.println("Done!"); Condition for Deadlock: - Mutual Exclusion - Hold & Wait - No-preemption - Circular Wait Result : Starting a1 Starting b2 Starting a1 Starting b2.

Thread Communication wait() Method void wait() throws InterruptedException void wait(long msec) throws InterruptedExc eption void wait(long msec, int nsec) throws Interr uptedexception Not Runnable status The wait() method allows a thread that is executing a synchronized method or statement block on that object to release the lock and wait for a notification from another thread. Notify Method void notify() The notify() method allows a thread that is executing a synchronized method or statement block to notify another thread that is waiting for a lock on this object. notifyall() Method void notifyall() 13 Producer & Consumer Example class Producer extends Thread { Queue queue; Producer(Queue queue) { this.queue = queue; int i = 0; while(true) { queue.add(i++); class Consumer extends Thread { String str; Queue queue; { Consumer(String str, Queue queue) this.str = str; this.queue = queue; while(true) { queue.remove()); System.out.println(str + ": " + class Queue { private final static int SIZE = 10; int array[] = new int[size]; int r = 0; int w = 0; int count = 0; synchronized void add(int i) { while(count == SIZE) { wait(); catch(interruptedexception ie) { ie.printstacktrace(); System.exit(0); array[w++] = i; if (w >= SIZE) w = 0; ++count; notifyall(); synchronized int remove() { while(count == 0) { wait(); catch(interruptedexception ie) { ie.printstacktrace(); System.exit(0); 14 int element = array[r++]; if (r >= SIZE) r = 0; --count; notifyall(); return element; class ProducerConsumers { public static void main(string args[]) { Queue queue = new Queue(); new Producer(queue).start(); new Consumer("ConsumerA", queue).start(); new Consumer("ConsumerB", queue).start(); new Consumer("ConsumerC", queue).start();

Exercise Step 1 (Bank Example 1) Slide 9 You can use several ways to change the result of step 1. As a way of those, I recommend you to use the synchronized statement block. Synchronized statement block - We can specify a statement or a block of code in a program as synchronzied. Form synchronized(theobject) { // statement block No other statements or statements blocks in the program that are synchronized on the object can execute while this statement is executing. 15 Exercise Step 2 (Bank Example 2) Slides 9-11 Remember the synchronized statement block and method Step 3 (Producer and Consumer 1) Slides 9-14 16