1 Java Programming Java Programming II Concurrent Programming: Threads ( I)

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

Locks (Java 1.5) Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until lock becomes available.
Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Slides 8c-1 Programming with Shared Memory Java Threads and Synchronization Review The following notes are based upon the Java tutorial at
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Concurrency…leading up to writing a web crawler. Web crawlers.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
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.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Concurrency - 1 Tasking Concurrent Programming Declaration, creation, activation, termination Synchronization and communication Time and delays conditional.
50.003: Elements of Software Construction Week 5 Basics of Threads.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Lecture 4 : JAVA Thread Programming
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
1 Java Threads and Synchronization Review Modified from slides taken from
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.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Multithreading. Chapter Goals To understand how multiple threads can execute in parallel To learn how to implement threads To understand race conditions.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Next week (July 21) –No class –No office hour. Problem Multiple tasks for computer –Draw & display images on screen –Check keyboard & mouse input –Send.
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.
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.
Threads.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
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.
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
1 G53SRP: Clocks and Time in Java Chris Greenhalgh School of Computer Science.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
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.
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
Chapter11 Concurrent. 集美大学 计算机工程学院 Java 程序设计 年 第二版 Concurrent ●Computer users take it for granted that their systems can do more than one thing.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
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.
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.
Advanced Programming Concurrency and Threads Advanced Programming. All slides copyright: Chetan Arora.
CSCD 330 Network Programming
Multithreading / Concurrency
Chapter 13: Multithreading
Java Multithreading.
Multithreading.
Threads Chate Patanothai.
Multithreading 2 Lec 24.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Threads and Multithreading
CSCD 330 Network Programming
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

1 Java Programming Java Programming II Concurrent Programming: Threads ( I)

2 Java Programming Contents  What is Thread?  Creating Threads  Using Runnable  Sleep, Interrupt, and Join Methods  Synchronization

3 Java Programming Concurrent Programming bal = a.getBalance(); bal += deposit ; a.setBalance(bal); bal = b.getBalance(); bal += deposit ; b.setBalance(bal); “a” is a thread object of some bank “b” is a thread object of another bank Two basic units in concurrent programming: Processes and Threads. Java Programming is mostly concerned with threads. A thread is called a sequence of steps executed on at a time. The single threaded programming model is the one most programmers use. The multithreading is called the analogue to having multiple real-world bank tellers.

4 Java Programming An Overview of Threads  What is a Thread? A sequence of execution within a process A Lightweight process – requires fewer resources than processes JVM manages and schedules threads Possible States: (1) new (2) ready (3) running (4) waiting (5) dead

5 Java Programming An Overview of Threads  Thread life cycle ReadyNew RunningWaiting Dead Sleep,wait,I/O

6 Java Programming How to Create Threads  Creating a Thread Object Thread worker = new Thread();  Two ways Using the Thread Class Using the Runnable interface  Using the Thread Class public class PingPong extends Thread { private String word; private int delay; public PingPong(String whatToSay, int delayTime) { word = whatToSay; delay = delayTime; } public void run() { try { for(;;) { System.out.print(word + “ “); Thread.sleep(delay); } } catch (InterruptedException e) { return; } public static void main(String[] args) { new PingPong(“ping”, 33).start(); new PingPong(“PONG”,100).start(); } Extend the Thread class Implement the run method

7 Java Programming Using Runnable  Using Runnable Interface Create a Thread object to pass object of implementation of the Runnable interface into Thread Constructor. Be useful when used with other application such as GUI or applet.. public class RunPingPong implements Runnable { private String word; private int delay; public PingPong(String whatToSay, int delayTime) { word = whatToSay; delay = delayTime; } public void run() { try { for(;;) { System.out.print(word + “ “); Thread.sleep(delay); } } catch (InterruptedException e) { return; } public static void main(String[] args) { Runnable ping = new RunPingPong(“ping”, 33); Runnable pong = new RunPingPong(“PONG”, 100); new Thread(ping).start(); new Thread(pong).start(); } Implement Runnable Interface Implement the run method Create Thread object

8 Java Programming Pausing Execution with Sleep  Thread.sleep method causes the current thread to suspend execution for a specified period.  Efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.  The sleep method can also be used for pacing and waiting for another thread with duties that are understood to have time requirements.  Sleep Methods static void sleep(long millis) static void sleep(long millis, int nanos) public class SleepMessages { public static void main(String args[]) throws InterruptedException { String importantInfo[] = { "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too" }; for (int i = 0; i < importantInfo.length; i++) { //Pause for 4 seconds Thread.sleep(4000); //Print a message System.out.println(importantInfo[i]); } It throws the InterruptedException.

9 Java Programming Join  The join method allows one thread to wait for the completion of another. t.join(); causes the current thread to pause execution until t's thread terminates.  Overloaded Methods void join() : Waits for this thread to die. void join(long millis) void join(long millis, int nanos) class ThreadM extends Thread { public void run() { try { for (int i = 0; i < 10; i++) { Thread.sleep(1000); System.out.println("ThreadM"); } } catch (InterruptedException ex) { ex.printStackTrace(); } } } class ThreadN extends Thread { public void run() { try { 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[]) { ThreadM tm = new ThreadM(); tm.start(); ThreadN tn = new ThreadN(); tn.start(); try { tm.join(); tn.join(); System.out.println("Both threads have finished"); } catch (Exception e) { e.printStackTrace(); } } join() method: Waits for this thread to die.

10 Java Programming Interrupts  An interrupt is an indication to a thread that it should stop what it is doing and do something else.  A thread sends an interrupt by invoking the “interrupt()” method on the Thread object for the thread to be interrupted.  Supporting Interruption If the thread is frequently invoking methods that throw InterruptedException, it simply returns from the run method after it catches that exception. Tests for the interrupt and exits the thread if one has been received. In more complex applications, to throw an InterruptedException for (int i = 0; i < importantInfo.length; i++) { try { Thread.sleep(4000); } catch (InterruptedException e) { //We've been interrupted: no more messages. return; } System.out.println(importantInfo[i]); } for (int i = 0; i < inputs.length; i++) { heavyCrunch(inputs[i]); if (Thread.interrupted()) { //We've been interrupted: no more crunching. return; } if (Thread.interrupted()) { throw new InterruptedException(); }

11 Java Programming Example: SimpleThreads.java public class SimpleThreads { //Display a message, preceded by the name of the current thread static void threadMessage(String message) { String threadName = Thread.currentThread().getName(); System.out.format("%s: %s%n", threadName, message); } private static class MessageLoop implements Runnable { public void run() { String importantInfo[] = { "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too" }; try { for (int i = 0; i < importantInfo.length; i++) { //Pause for 4 seconds Thread.sleep(4000); //Print a message threadMessage(importantInfo[i]); } } catch (InterruptedException e) { threadMessage("I wasn't done!"); } } // end of run } // end of public static void main(String args[]) throws InterruptedException { //Delay, in milliseconds before we interrupt MessageLoop //thread (default one hour). long patience = 1000 * 60 * 60; When this thread receives an interrupt, it happens.

12 Java Programming Example: SimpleThreads.java //If command line argument present, gives patience in seconds. if (args.length > 0) { try { patience = Long.parseLong(args[0]) * 1000; } catch (NumberFormatException e) { System.err.println("Argument must be an integer."); System.exit(1); } threadMessage("Starting MessageLoop thread"); long startTime = System.currentTimeMillis(); Thread t = new Thread(new MessageLoop()); t.start(); threadMessage("Waiting for MessageLoop thread to finish"); //loop until MessageLoop thread exits while (t.isAlive()) { threadMessage("Still waiting..."); //Wait maximum of 1 second for MessageLoop thread to finish. t.join(1000); if (((System.currentTimeMillis() - startTime) > patience) && t.isAlive()) { threadMessage("Tired of waiting!"); t.interrupt(); //Shouldn't be long now -- wait indefinitely t.join(); } threadMessage("Finally!"); } The source code is at the “/home/course/java2/code/Thread/SimpleThreads.java” When elapsed time is larger than the patience, it send interrupt to the thread “t”.

13 Java Programming Synchronization If one thread invokes a synchronized method on an object, the lock of that object is first acquired, the method body executed, and then the lock released. Another thread invoking a synchronized method on that same object will block until the lock is released  Synchronized Methods : protection from interference in a multithreaded environment acquire lock release lock synchronized method acquire lock release lock wait to acquire lock synchronized method

14 Java Programming Synchronized Methods  Example Code public class BankAccount { private long number; // account number private long balance; // current balance (in cents) public BankAccount(long initialDeposit) { balance = initialDeposit; } synchronized public long getBalance() { return balance; } private final void setBalance(double amount) { balance = amount; } synchronized public void deposit(double amount) { double bal = getBalance(); bal += amount; setBalance(bal); } // … rest of methods } *Example: Refer to the “/home/course/java2/code/Thread/TellerTest.java” When a synchronized method is invoking, other synchronized methods in the class cannot be invoked, but non- synchronized methods can be invoked.

15 Java Programming Locking Objects with Synchronized Methods thread 1 run() { obj1.method2(); } thread 2 run() { obj1.method3(); obj1.method1(); obj2.method1(); } obj 1 synchronized method1() synchronized method2() method3() thread 3 run() { obj2.method3(); obj2.method2(); } obj 2 synchronized method1() synchronized method2() method3() OK. method2() Not busy Always OK. No! Not while method2() for obj1 is executing No! Not while method1() for obj2 is executing OK. method1() Not busy Always OK.