In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.

Slides:



Advertisements
Similar presentations
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
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.
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
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.
Programming in Java; Instructor:Alok Mehta Threads1 Programming in Java Threads.
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.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads Just Java: C10–pages 251- C11–pages 275-
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Lecture 4 : JAVA Thread Programming
Consider the following Java code Race Conditions public class Shared { private int data; public Shared() { data = 0; } public void setData(int r) { data.
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)
Online Appointment Book Implement a Client/Server application for an online appointment book. Client should be a Graphical User Interface application.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Consider the following Java code Race Conditions public class Shared { private int data; public Shared() { data = 0; } public void setData(int r) { data.
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.
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.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
Threading Eriq Muhammad Adams J
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.
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.
Threading and Concurrency COM379T John Murray –
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.
Java 3: Odds & Ends Advanced Programming Techniques.
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.
6.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts with Java – 8 th Edition Module 6: Process Synchronization Codes.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
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.
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 Chapter 19 Multithreading. 2 Objectives F To understand the concept of multithreading and apply it to develop animation (§19.2). F To develop thread.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
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.
Distributed and Parallel Processing George Wells.
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multithreading / Concurrency
Multi Threading.
Multithreading.
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Condition Variables and Producer/Consumer
Multithreading.
Condition Variables and Producer/Consumer
Java Based Techhnology
Multithreading.
13: Concurrency Definition:  A thread is a single sequential flow of control within a program. Some texts use the name lightweight process instead of thread.
برنامه‌نویسی چندنخی Multi-Thread Programming
Computer Science 2 06A-Java Multithreading
Multithreading in java.
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static void main method. Two steps are needed to execute a separate thread: 1) an object (inheriting Thread / conforming to Runnable) must be created. 2) the method must be called on the thread object. This invokes a method called run(). Thread.currentThread() is a static method call that will return the thread object associated with current execution Thread.currentThread().sleep(100); Example This statement causes the executing code to be suspended for 100 milliseconds (0.1 sec.) (note: sleep is a static method.)

public class Driver { public static void main(String args[]) { MyThread threadA, threadB; threadA = new MyThread(); threadA.start(); threadB = new MyThread(); threadB.start(); runAwhile(); System.out.println("The Driver thread is finished."); } public static void runAwhile() { try { //delay for a random number of millisec. Thread.currentThread().sleep((int)(Math.random()*1000)); } catch (InterruptedException e) {} }

public class MyThread extends Thread { public void run() { for (int j=1; j<=5; j++) { System.out.println(Thread.currentThread()+" loop counter:"+j); runAwhile(); } public static void runAwhile() { try { //delay for a random number of millisec. Thread.currentThread().sleep((int)(Math.random()*1000)); } catch (InterruptedException e) {} } The Thread class is the superclass for creating thread objects.

public class Driver { public static void main(String args[]) { MyThread threadA, threadB; threadA = new MyThread(); threadA.start(); threadB = new MyThread(); threadB.start(); runAwhile(); System.out.println("The Driver thread is finished."); } public static void runAwhile() { try { //delay for a random number of millisec. Thread.currentThread().sleep((int)(Math.random()*1000)); } catch (InterruptedException e) {} } Thread[Thread-0,5,main] loop counter:1 Thread[Thread-1,5,main] loop counter:1 Thread[Thread-0,5,main] loop counter:2 Thread[Thread-0,5,main] loop counter:3 The Driver thread is finished. Thread[Thread-1,5,main] loop counter:2 Thread[Thread-0,5,main] loop counter:4 Thread[Thread-1,5,main] loop counter:3 Thread[Thread-1,5,main] loop counter:4 Thread[Thread-0,5,main] loop counter:5 Thread[Thread-1,5,main] loop counter:5

Suspend a process for the indicated number of milliseconds. sleep (int millisec) - from Thread Initiate the execution of a thread object, concurrent with the executing thread. The new thread executes its run() method. start () - from Thread A thread terminates when its run() method completes execution. Thread termination Suspend the process in the waiting list associated with the object. wait () - from Object Resume one process in the waiting list associated with the object. (Note, this is different than a signal - nothing occurs when no threads are suspended.) notify () - from Object Resume all processes in the waiting list associated with the object. notifyAll () - from Object Causes this thread to allow other threads to execute if they are suspended awaiting the object this thread owns. yield () - from Thread

NewRunnableDeadBlocked

Every Java object can be locked in one of two ways: When a thread has locked an object, any other thread attempting a lock will be suspended (blocked) until the lock is released. A synchronized instruction forms a critical section. wait, notify and notifyAll can only be called upon a locked object. synchronized(objectRef) { // the objectRef object is locked for the duration of this instruction.... } synchronized returnType someMethod (parmList) { // the this object is locked for the duration of this method call.... } synchronized methods in the same class create a monitor. Calling wait unlocks the object and adds the thread to the object’s wait set.

public class LockableObject { private int semaValue; public LockableObject() { semaValue = 0; } public synchronized void lockedWait() { semaValue--; if (semaValue < 0) try { wait(); } catch (InterruptedException e) {} } public synchronized void lockedSignal() { semaValue++; if (semaValue <= 0) notify(); }

public class MyThread extends Thread { public LockableObject semaphore = new LockableObject(); public void run() { semaphore.lockedWait(); for (int j=1; j<=5; j++) { System.out.println(Thread.currentThread()+" loop counter:"+j); runAwhile(); } public void runAwhile() {... } } public class Driver { public static void main(String args[]) { MyThread threadA, threadB; threadA = new MyThread(); threadA.start(); threadB = new MyThread(); threadB.start(); System.out.println("The Driver has started other threads."); threadA.semaphore.lockedSignal(); threadB.semaphore.lockedSignal(); try { threadA.join(); threadB.join(); } catch (InterruptedException e) {} System.out.println(“All threads are finished!”); }

Producer thread monitorObj.depositData( data ); Consumer thread monitorObj.removeData( data ); public class Monitor { private final int numberOfBuffers = 100; private int buffersInUse = 0; public Monitor() // constructor method { } public synchronized void depositData( int data ) { while (buffersInUse == numberOfBuffers) try { wait(); } catch (InterruptedException e) {} //placeInNextAvailableBuffer(Data); buffersInUse++; notifyAll(); } public synchronized int removeData() { while (buffersInUse == 0) try { wait(); } catch (InterruptedException e) {} //remove data from oldest buffer buffersInUse--; notifyAll(); return dataJustRemoved; }

Returns true unless the thread is dead. isAlive () - from Thread Assigns a priority to a thread. Higher numbers mean higher priority to execute. setPriority (int p) - from Thread Sets a thread as a daemon or not. Daemons can continue to run in the background when a program terminates. setDaemon (boolean on) - from Thread suspend (), resume (), stop () - from Thread All are deprecated! deadlock proneunsafe because the thread unlocks all monitors it locked If the thread is blocked via wait or join, then InterruptException is thrown. If the thread is blocked for I/O, then ClosedByInterruptException is thrown. interrupt () - from Thread Causes the executing thread to suspend awaiting the obj thread to die. obj.join () - from Thread