Presentation is loading. Please wait.

Presentation is loading. Please wait.

Multi Threading.

Similar presentations


Presentation on theme: "Multi Threading."— Presentation transcript:

1 Multi Threading

2 A Program under execution is called Process, i
A Program under execution is called Process, i..e when a Program is loaded into main memory and starts running, it is Process. A Thread is Light Weight Process. A Process under execution has below segments in memory Code, Data, Stack, Heap. But a thread may have only Stack or Heap, and other segments are shared with the Main thread. A Thread is a separate flow of execution. It is required to create multiple Threads to perform multiple actions simultaneously. Hence, using multi threading is a cheaper solution(uses less Memory) compared to using multiple processes. Java has built in support for Multi Threading.

3 Code(code under execution) Stack
Data(to store static data) Heap Stack(for method invocation) Snapshot of Running Thread Heap(dynamic memory allocation) Snapshot of Running Process

4 Hence it consumes less memory and starts faster, compared to a Process.
A process under execution has two cycles. CPU Cycle I/O Cycle One more advantages of Thread over Process, is Threads use CPU more effectively, compared to Processes. When one thread performs I/O, another thread can be busy with CPU. And hence, Effective usage of CPU Time. Actually, CPU executes only one Thread at a time. But CPU switches between different Threads of a Process, hence we feel that multiple threads are executed simultaneously. Java has built in support for Multithreading.

5 In Java there are two ways to create and start a new Thread.
By extending from java.lang.Thread class 2. By implementing java.lang.Runnable interface

6 Below are steps involved to create and start Thread, using Thread class
Write a class which extends from Thread class. Override public void run() method in class created above. Write business logic which need to be executed in new thread, in run() method of step2. In main method Create an object of Class of Step1 With the object, invoke start() method

7 Thread.sleep(2000); causes delay in execution of current thread.
Join() method The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.

8 Below are steps involved to create and start Thread, using Runnable interface
Write a class which implements Runnable interface. Implement public void run() method in class created above. Write business logic which need to be executed in new thread, in run() method of step2. In main method Create an object of Class of Step1 Create a Thread object, by passing object(created in step 4) as parameter to Thread constructor With the Thread object(created in step 5), invoke start() method

9 Thread priority By default all the threads created, get medium priority, unless a specific priority explicitly is set to the thread. Below are the priority related constants provided in Thread class. Thread.MIN_PRIORITY (value is 0) Thread.NORM_PRIORITY (value is 5, which is default priority) Thread.MAX_PRIORITY (value is 10) Any numeric value between 0 and 10 can be set as priority to a Thread. Below are priority related methods provided in Thread class void setPriority(int priority); int getPriority(); A thread with high priority gets allocated with more CPU time, compared to threads with relatively low priority threads. Hence a thread with high priority threads executes faster, compared to low priority threads.

10 synchronized keyword Synchronized keyword can be used with either a method or a block. A method declared as synchronized can be executed by only one thread at a time. once the thread starts executing a synchronized method, the thread is not interrupted, until the thread completes execution of the method. Instead of declaring complete method as synchronized, it is possible to declare a block with few statements as synchronized. In other words, a method or block declared as synchronized is atomic, which means it gets executed completely without interruption in between. Synchronized keyword need to be used only where ever required, when it is over used, it may adversely affect the performance of Application.

11 public static void main(String args[]) {
Thread and Inner Class Instead of creating a dedicated outer class for a Thread, an inner class(with run method) can be created for a Thread. Below is sample code of the same #1. public static void main(String args[]) { //Named object and Anonymous inner class Thread t1=new Thread(){ public void run(){ //Thread code here } }; t1.start(); //code running in main thread #2. public static void main(String args[]) new Thread( new Runnable() { public void run() { //thread code here }).start(); //code in main thread here

12 These methods can be used to solve producer consumer related problems.
wait(), notify() and notifyAll() As known above methods are final methods defined in java.lang.Object class. Hence these methods are available in each and every class, because Object class is base class of all classes, in Java. These methods can be invoked only from synchronized block or synchronized method. wait(); - It tells the calling thread to give up the lock and go to sleep until some other thread enters calls notify() method on same object. notify(); -It wakes up one single thread that called wait() on the same object. notifyAll(); - It wakes up all the threads that called wait() on the same object. These methods can be used to solve producer consumer related problems.

13 Downloader Thread downloads packets, adds to Queue.
Packet Queue Display Thread, which reads packets, from Queue, and displays/renders on screen Downloader Thread, which downloads packets, and puts in to Queue Here Display Thread, need to continuously check(with a infinite loop or so) Packet Queue, to find if new Packets are available, which may not be a professional approach. As continuously checking Packet Queue, may waste CPU time, and may adversely affect performance of overall Application. This problem can be solved better, by using wait() and notify(). Below are the steps involved… Downloader Thread downloads packets, adds to Queue. Calls notify() method on Queue, which wakes up Display Thread. Now display Thread reads packets from Queue, processes them. Calls wait() method on Queue, which goes on sleep, until notify() is called by Downloader Thread.

14 ThreadPool What is Thread Pool? It’s a pool of worker threads with life cycle as follows: 1. Assign a new task to execute 2. Execute it 3. Go back to Pool, waiting for next task Why Thread Pools? In many server applications, we may want to process each client request in parallel. For that matter, we can choose traditional approach of creating one thread per request. Disadvantage of using Traditional one thread per task approach The overhead of creating a new thread for each request is significant. Server that processing requests can spend more time and consume more system resources in creating and destroying threads than it would processing actual client requests. Another Advantage of Thread pool is limit maximum number of threads running at any point of time.

15 Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlocks can occur in Java when the synchronized keyword causes the executing thread to block while waiting to get the lock, associated with the specified object. Since the thread might already hold locks associated with other objects, two threads could each be waiting for the other to release a lock. In such case, they will end up waiting forever.

16 Deadlock example Thread t1 Thread t2 Step3 Tries to Lock str2 Step1


Download ppt "Multi Threading."

Similar presentations


Ads by Google