Threads.

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Advertisements

Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
Multithreading.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
Internet Software Development More stuff on Threads Paul Krause.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Java Programming: Advanced Topics
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.
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.
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
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.
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.
Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
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.
1 5.0 Garbage collector & Threads : Overview Introduction: In this module we discuss the merits and demerits of automated garbage collection over manual.
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.
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.
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
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.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
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.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
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.
1 Multithreading in Java THETOPPERSWAY.COM. 2 Outline  Multithreading & Thread Introduction  Creating threads  Thread Life Cycle  Threads priorities.
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
CSCD 330 Network Programming
Multithreading / Concurrency
Multithreading Lec 23.
Chapter 13: Multithreading
Multi Threading.
Java Multithreading.
Multithreading.
Multithreaded Programming in Java
Threads Chate Patanothai.
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
21 Threads.
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Multithreading in java.
Threads and Multithreading
CSCD 330 Network Programming
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Threads

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

Process-based multitasking process-based multitasking, which allows processes(i.e., programs) to run concurrently on the computer. A familiar example is running the spreadsheet program while also working with the word-processor.

Thread-based multitasking Thread-based multitasking, which allows parts of the same program to run concurrently on the computer. A familiar example is a wordprocessor that is printing and formatting text at the same time

Overview of Threads A thread is an independent sequential path of execution within a program. Many threads can run concurrently within a program. At runtime, threads in a program exist in a common memory space and can, therefore, share both data and code (i.e. they are lightweight compared to processes). They also share the process running the program.

User Threads/Daemon Threads The runtime environment distinguishes between user threads and daemon threads. As long as a user thread is alive, the JVM does not terminate. A daemon thread is at the mercy of the runtime system: it is stopped if there are no more user threads running, thus terminating the program. Daemon threads exist only to serve user threads.

The Main Thread When a standalone application is run, a user thread is automatically created to execute the main() method of the application. This thread is called the main thread. If no other user threads are spawned, the program terminates when the main() method finishes executing.

Thread Creation A thread in Java is represented by an object of the Thread class. implementing threads is achieved in one of two ways: Implementing the java.lang.Runnable interface Extending the java.lang.Thread class

Extending java.lang.Thread The simplest way to define code to run in a separate thread is to ■ Extend the java.lang.Thread class. ■ Override the run() method. It looks like this: class MyThread extends Thread { public void run() { System.out.println("Important job running in MyThread"); } }

The overloaded run(String s) method will be ignored by the Thread class unless you call it yourself. The Thread class expects a run() method with no arguments, class MyThread extends Thread { public void run() { System.out.println("Important job running in MyThread"); } public void run(String s) { System.out.println("String in run is " + s);}}

Implementing the Runnable Interface When Class has extends different super class then class cant extends Thread class. Therefore class can implements the Runnable interface to create a thread. The Runnable interface has the following specification, comprising one abstract method declaration: public interface Runnable { void run(); }

public class RunnableThreadTest implements Runnable{ @Override public void run() { System.out.println(“Runnable Thread Test”); } public static void main(String[] args) { RunnableThreadTest runnable = new RunnableThreadTest(); Thread t1 = new Thread(runnable); t1.start(); } }

Run()/Start() methods Run method execute when calling to start method. MyThread t = new MyThread(); t.start(); If call t.run() method called then thread will not create. Just method calling only. Start() method cannot call same thread object more than once time. Then java.lang.IllegalThreadStateException pop up.

Thread Scheduler The thread scheduler is the part of the JVM that decides which thread should run at any given moment, and also takes threads out of the run state. Assuming a single processor machine, only one thread can actually run at a time. Only one stack can ever be executing at one time. The order in which runnable threads are chosen to run is not guaranteed.

Thread States and Transitions A thread can be only in one of five states. ■ New This is the state the thread is in after the Thread instance has been created, but the start() method has not been invoked on the thread. It is a live Thread object, but not yet a thread of execution. At this point, the thread is considered not alive.

Thread States and Transitions ■ Runnable This is the state a thread is in when it's eligible to run, but the scheduler has not selected it to be the running thread. A thread first enters the runnable state when the start() method is invoked, but a thread can also return to the runnable state after either running or coming back from a blocked, waiting, or sleeping state. When the thread is in the runnable state, it is considered alive.

Thread States and Transitions ■ Running . This is the state a thread is in when the thread scheduler selects it (from the runnable pool) to be the currently executing process. A thread can transition out of a running state for several reasons.

Thread States and Transitions

Thread States and Transitions Not Runnable(Waiting/blocked/sleeping) This is the state a thread is in when it's not eligible to run. This is really three states combined into one,but they all have one thing in common: the thread is still alive, but is currently not eligible to run. In other words, it is not runnable. May be blocked waiting for a resource May be sleeping because the thread's run code tells it to sleep for some period of time, May be waiting, because the thread's run code causes it to wait

Thread States and Transitions ■ Dead A thread is considered dead when its run() method completes. It may still be a viable Thread object, but it is no longer a separate thread of execution. Once a thread is dead, it can never be brought back to life! (The whole "I see dead threads" thing.) If you invoke start() on a dead Thread instance, you'll get a runtime (not compiler) exception.

Thread Constructors Thread() Thread(Runnable target) Thread(Runnable target, String name) Thread(String name) Thread(ThreadGroup group, Runnable target) Thread(ThreadGroup group, Runnable target, String name) Thread(ThreadGroup group, Runnable target, String name, long stackSize) Thread(ThreadGroup group, String name)

java.lang.Thread Methods public static void sleep(long millis) throws InterruptedException public static void yield() public final void join() throws InterruptedException public final void setPriority(int newPriority) Note that both sleep() and join() have overloaded versions not shown here.

java.lang.Object Methods Every class in Java inherits the following three thread-related methods: public final void wait() throws InterruptedException public final void notify() public final void notifyAll() The wait() method has three overloaded versions

Deprecated Thread class Methods public void destroy() public final void resume() public final void stop() public final void suspend()

public static void sleep(long m) sleep() method in the Thread class will cause the currently running thread to temporarily pause its execution and transit to the Not Runnable state. The thread will sleep for at least the time specified in its argument. Before transitioning to the Ready to-run state where it takes its turn to run again. Throws InterruptedException. sleep() time is not a guarantee that the thread will start running again as soon as the time expires and the thread wakes.

public static void sleep(long m)

public class SleepingThreadTest extends Thread { public void run() { try { System.out.println("Thread Start"); Thread.sleep(10000); } catch (InterruptedException ex) { }} public static void main(String[] args) { SleepingThreadTest obj1 = new SleepingThreadTest(); obj1.start(); SleepingThreadTest obj2 = new SleepingThreadTest(); obj2.start(); obj2.start(); }}

public static void yield() yield() method defined in the Thread class, may cause the current thread in the Running state to transit to the Ready-to-run state. It is possible that if there are no threads in the Ready-to-run state, this thread can continue executing. If there are other threads in the Ready-to-run state, their priorities can influence which thread gets to execute.

public static void yield()

Thread's Priority Priorities are set using a positive integer, usually between 1 and 10, and the JVM will never change a thread's priority. Although the default priority is 5. Use setPriority(int value) method to set the priority. Thread class has the three following constants (static final variables) that define the range of thread priorities. Thread.MIN_PRIORITY (1) Thread.NORM_PRIORITY (5) Thread.MAX_PRIORITY (10)

Thread's Priority FooRunnable r = new FooRunnable(); Thread t = new Thread(r); t.setPriority(8); t.start();

public final void join() The non-static join() method of class Thread lets one thread "join onto the end” of another thread. If you have a thread B that can't do its work until another threadA has completed its work, then you want thread B to "join" thread A. This means that thread B will not become runnable until A has finished (and entered the dead state). Thread t = new Thread(); t.start(); t.join();

public final void join() t.join() means "Join me (the current thread) to the end of t, so that t must finish before I (the current thread) can run again. Throws InterruptedException.

Sleep()/yield()/join() ■ A call to sleep() Guaranteed to cause the current thread to stop executing for at least the specified sleep duration (although it might be interrupted. Before its specified time). ■ A call to yield() Not guaranteed to do much of anything, although typically it will cause the currently running thread to move back to runnable. so that a thread of the same priority can have a chance. ■ A call to join() until the thread it joins with (in other words, the thread it calls join().

Synchronizing Code Threads share the same memory space, i.e., they can share resources. How ever, there are critical situations where it is desirable that only one thread at a time has access to a shared resource. For example, crediting and debiting a shared bank account concurrently among several users without proper discipline, will jeopardize the integrity of the account data. Java provides high-level concepts for synchronization in order to control access to shared resources.

Non Synchronize Method private void makeWithdrawal(int amt) { if (acct.getBalance() >= amt) { System.out.println(Thread.currentThread().getName() + " is going to withdraw"); try { Thread.sleep(500); } catch(InterruptedException ex) { } acct.withdraw(amt); + " completes the withdrawal"); } else { System.out.println("Not enough in account for " + Thread.currentThread().getName() + " to withdraw " + acct.getBalance());}}

Locks A lock (also called a monitor) is used to synchronize access to a shared resource. A lock can be associated with a shared resource. Threads gain access to a shared resource by first acquiring the lock associated with the resource. At any given time,at most one thread can hold the lock and thereby have access to the shared resource.

Synchronization and Locks Remember the following key points about locking and synchronization: ■ Only methods (or blocks) can be synchronized, not variables or classes. ■ Each object has just one lock. ■ Not all methods in a class need to be synchronized. A class can have both synchronized and non-synchronized methods.

Synchronization and Locks ■ If two threads are about to execute a synchronized method in a class, and both threads are using the same instance of the class to invoke the method, only one thread at a time will be able to execute the method. The other thread will need to wait until the first one finishes its method call. In other words, once a thread acquires the lock on an object, no other thread can enter any of the synchronized methods in that class (for that object).

Synchronized method private synchronized void makeWithdrawal(int amt) { if (acct.getBalance() >= amt) { System.out.println(Thread.currentThread().getName() + " is going to withdraw"); try { Thread.sleep(500); } catch(InterruptedException ex) { } acct.withdraw(amt); " completes the withdrawal"); } else { System.out.println("Not enough in account for " + Thread.currentThread().getName() + " to withdraw " + acct.getBalance());} }

Synchronized method ❑ synchronized methods prevent more than one thread from accessing an object's critical method code simultaneously. ❑ You can use the synchronized keyword as a method modifier, or to start a synchronized block of code. ❑ To synchronize a block of code (in other words, a scope smaller than the whole method), you must specify an argument that is the object whose lock you want to synchronize on.

Synchronized method ❑ While only one thread can be accessing synchronized code of a particular instance, multiple threads can still access the same object's unsynchronized code. ❑ When a thread goes to sleep, its locks will be unavailable to other threads. ❑ static methods can be synchronized, using the lock from the java.lang.Class instance representing that class.

Synchronized Block Example public void doStuff() { synchronized(this) { System.out.println("synchronized"); }

Static Method Synchronized Block Example If the method is defined in a class called MyClass, the equivalent code is as follows: public static int getCount() { synchronized(MyClass.class) { return count; }}

Static Method Synchronized Block Example MyClass.class thing? That's called a class literal. It's a special feature in the Java language that tells the compiler (who tells the JVM): go and find me the instance of Class that represents the class called MyClass.

Static Method Synchronized Block Example You can also do this with the following code: public static void classMethod() { Class cl = Class.forName("MyClass"); synchronized (cl) { // do stuff }

Communicating with Objects by Waiting and Notifying ❑ The wait() method lets a thread say, "there's nothing for me to do now, so put me in your waiting pool and notify me when something happens that I care about." Basically, a wait() call means "wait me in your pool," or "add me to your waiting list." ❑ The notify() method is used to send a signal to one and only one of the threads that are waiting in that same object's waiting pool. ❑ The notify() method can NOT specify which waiting thread to notify.

Communicating with Objects by Waiting and Notifying ❑ The method notifyAll() works in the same way as notify(), only it sends the signal to all of the threads waiting on the object. ❑ All three methods—wait(), notify(), and notifyAll()—must be called from within a synchronized context! A thread invokes wait() or notify() on a particular object, and the thread must currently hold the lock on that object.

Thank You