1 Threads  Sequential Execution: Here statements are executed one after the other.They consider only a single thread of execution, where thread is an.

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

Practice Session 7 Synchronization Liveness Guarded Methods Model
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Concurrency and Thread Yoshi. Two Ways to Create Thread Extending class Thread – Actually, we need to override the run method in class Thread Implementing.
Multithreading The objectives of this chapter are:
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Multithreading.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Collage of Information Technology University of Palestine Advanced programming MultiThreading 1.
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
1 Concurrent Languages – Part 1 COMP 640 Programming Languages.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
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.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
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.
1 Web Based Programming Section 8 James King 12 August 2003.
Java Threads 1 1 Threading and Concurrent Programming in Java Queues D.W. Denbo.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
Synchronizing threads, thread pools, etc.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
1 Introduction to Threads Computers can perform many tasks concurrently – download a file, print a file, receive , etc. Sequential languages such.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading Chapter Introduction Consider ability of _____________ to multitask –Breathing, heartbeat, chew gum, walk … In many situations we.
Multithreading Chapter Introduction Consider ability of human body to ___________ –Breathing, heartbeat, chew gum, walk … In many situations we.
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.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Java 3: Odds & Ends Advanced Programming Techniques.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Monitors and Blocking Synchronization Dalia Cohn Alperovich Based on “The Art of Multiprocessor Programming” by Herlihy & Shavit, chapter 8.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
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 G53SRP: Java Concurrency Control (2) – wait/notify Chris Greenhalgh School of Computer Science.
L6: Threads “the future is parallel” COMP206, Geoff Holmes and Bernhard Pfahringer.
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.
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.
A brief intro to: Parallelism, Threads, and Concurrency
Multithreading / Concurrency
Multithreading Lec 23.
Multi Threading.
Multithreaded Programming in Java
Threads Chate Patanothai.
Multithreading Chapter 23.
Synchronization Lecture 23 – Fall 2017.
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Threads and Multithreading
Concurrent programming
Software Engineering and Architecture
CMSC 202 Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

1 Threads  Sequential Execution: Here statements are executed one after the other.They consider only a single thread of execution, where thread is an individual sequential actvity.

2  Java program may execute several threads concurrently. e.g one part of program may continue computing while another part is blocked waiting for input.  Java.lang.Thread is fundamental thread class.

3 The Main Thread When a java program starts up, one thread begins running immediately.This is called the main thread of the program. From the main thread all other child threads will be spawned. The main thread is the last thread to finish the execution

4  There are two ways to define a Thread. 1) To subclass Thread, override the run() method and then instantiate the subclass and call start() method. 2) To define a class that implements a Runnable ( it defines run() method ) and then pass instance of this object to Thread constructor and then call start() method In either case result is a thread object, where the run() method is the body of the thread. When we call start method of the thread object, the interpreter creates a new thread to execute the run() method.This new thread continues to run until the run() method exits.Meanwhile, the original thread continues running itself, starting with the statement following the start() method.

5 Thread Life Cycle  A thread can be in one of six states.These states are represented by enumerated data type Thread.State. Thread State can be obtained by getState() method.  NEW : The thread has been created but its start method has not yet been called.  RUNNABLE: Thread is executing in the JVM

6  BLOCKED: The thread is not running as it is waiting to acquire a lock so that it can enter a synchronized method or block.  WAITING: The thread is not running as it has called one of the following method.

7  »Object.wait with no timeout »Thread.join with no timeout : It waits for thread to die(eg. Let u be a thread,u.join(): It waits for thread u to die )

8 TIMED WAITING : The thread is not running as it has called Thread.sleep() or has called Object.wait() or Thread.join() with a timeout value. TERMINATED : The thread has completed execution.Its run() method has exited normally or by throwing an exception.

9 Thread Priorities:  Threads can run at different priority levels.A thread at given priority level can not run if threads having higher priority are waiting to run. Thread.MAX_PRIORITY : 10 Thread.MIN_PRIORITY : 1 Thread.NORM_PRIORITY : 5  All threads are examined and highest priority thread that is ready to run is given the CPU.  A thread can be preempted by higher priority thread.( Preemptive Multitasking)

10  We can get and set priority by using getPriority() and setPriority().  we need repetitive tasks at fixed intervals.

11 Locks and Synchronization  Threads are executed concurrently,so when multiple concurrent threads access the same data,data inconsistency may arise.  To avoid this thread should synchronize the access in shared state.A single lock is associated with every object.A lock can be held by atmost one thread at a time on an object.  A thread may explictly request the lock on an object by executing synchronized statement.  At a time only one thread can execute synchronized block

12  syntax: synchronized( expression) block statement  The expression must have reference type.The expression must evaluate to a non null reference say Obj.  After the evaluation of an expression thread becomes locking on the object Obj.  When thread obtains the lock on object Obj, it becomes enabled and may be running so the block statement is executed.  When block statement terminates or is exited by return or break or by throwing an exception, the lock on o is released.  If static method is declared synchronized, the thread obtains the lock on the class.

13 Class Buffer { private int item; private boolean empty=true; public int get(){ synchronized(this){ while(empty) try{ this.wait();} catch(InterruptedException e){}; empty=true; this.notify(); return item; }// end of syn block } public void put( int i){ synchronized(this){ while(!empty) try{ this.wait();}catch(InterruptedException e){}; empty=false item=i; this.notify(); }

14  The Collection, Set,Map, List implementation do not have synchronized methods.  Synchronized wrapper objects. eg. List Synlist=Collections.synchronizedList(list); Map Synmap=Collections.synchronizedMap(map);

15 A Lock Object  If we use synchronized statements,the lock we acquire is block scoped.  Java 5.0 provides an alternative :A Lock object that we can explictly lock and unlock.  package java.util.concurrent.locks has interfaces and classes for this implementation  Interface lock has two mehtods:lock() and unlock which explictly locks or unlocks the objects

16 Deadlock :- It occurs when two threads end up waiting for each other to release the lock they need.Here neither can proceed as neither can release the lock, so both threads stop running. The following code is likely to create Deadlock.

17 DeadLock Detection: lock () method of the lock interface is able to detect Deadlock circumstances and throws unchecked exception.

18 The Executor and Executor Service Before Java 5.0, Threads' execution cycles are tied to the code they actually perform. Executor interface defines a means of supplying threads to an object (which implements the Executor interface), and letting that object deal with timing and running of the threads. we need to add Runnable objects to the Executor (which generally adds them to an internal queue), and the Executor then uses its own threads to peel off the objects and run them.

19 Executor Service It extends the Executor and adds the ability to execute Callable objects. Callable is something like Runnable.It puts code in call() instead of run(). Here we have to submit the task which returns the future object that is parameterized with the type of result.

20 Blocking Queues  New feature in Java 5.0  Defines put() and take() methods.  ArrayBlocking Queue : -Fixed capacity  LinkedBlocking Queue: -bsaed on linked list data structure. -default size :unbounded  PriorityBlockingQueue: -unbounded -not a FIFO queue, it orders its elements based on a comparator object.

21 DelayedQueue: -It implements Delayed interface. -It orders the elements by how long they are delayed. -elements can not be removed until their delay has elapsed. SynchronousQueue: -zero capacity queue. -each put must wait for a take, and vice versa

22 Atomic Variables It support lock-free thread-safe programming on single variables. Problems with locking:  With locking, if one thread attempts to acquire a lock that is already held by another thread, the thread will block until the lock becomes available.  Lock has some other hazards as well, such as deadlock (which can happen when multiple locks are acquired in an inconsistent order).  Locks are simply a relatively "heavyweight" for managing a simple operation such as incrementing a counter. It would be nice if there were a finer-grained mechanism for reliably managing concurrent updates to individual variables.

23 Hardware Synchronization  most modern processors include support for multiprocessing.They have instruction set supporting the multiprocessing.  CAS(compare and swap):mem location, expected value, new value  CAS allows an algorithm to execute without fear of another thread modifying the variable in the meantime, because if another thread did modify the variable, the CAS would detect it (and fail) and the algorithm could retry the operation.

24  a lock-free algorithm requires only that some thread always make progress.  The atomic variable classes all expose a compare-and-set primitive (similar to compare- and-swap), which is implemented using the fastest native construct available on the platform (compare-and-swap).  if ten threads each execute some operation once, in the worst case each thread will have to retry at most nine times.

25 public class Counters{ AtomicInteger count=new AtomicInteger(5); public int getCount(){ int result; do{ result=count.get(); } while(!count.compareAndSet(result,result+1) ); return result; }

26