Java Technology: Threads

  • Uploaded by: vetrivendhan
  • 0
  • 0
  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Java Technology: Threads as PDF for free.

More details

  • Words: 1,351
  • Pages: 27
Java Technology Threads

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

Session Plan 

Life cycle of threads



Using Thread class and its methods



Synchronization



Deadlock



Inter-Thread communication

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

2

Threads 

Thread is an object it has variables and methods that lives and dies on the heap



But a thread of execution is an individual process (‘light weight process’) that has its own call stack.



In java there is one thread per call stack even if you don’t create thread there will be a default thread running called main thread ie.,main method.

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

3

Motivation for Threads in Java 

Threads have become prominent due to trends in 

Software design 



More naturally expresses inherently parallel tasks

Performance 

Scales better to multiprocessor systems

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

4

Creating Threads 

Two approaches 

Thread class public class Thread extends Object { … }



Runnable interface public interface Runnable { public void run(); // work ⇒ thread }

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

5

A Runnable Object 

The Thread object’s run() method calls the Runnable object’s run() method





Allows threads to run inside any object, regardless of inheritance Example – an applet that is also a thread

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

6

Execution of Thread 

Threads are scheduled according to their priority w.r.t. other threads in the ready queue



The highest priority runnable thread is always selected for execution above lower priority threads



When multiple threads have equally high priorities, only one of those threads is guaranteed to be executing

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

7

Priority in Thread 

Every thread has a priority



When a thread is created, it inherits the priority of the thread that created it (normal-5, maximum-10,minimum-1)



The priority values range from 1 to 10, in increasing priority



The priority can be adjusted and may be obtained using setPriority(), getPriority() method

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

8

Life cycle methods 



void start() 

Creates a new thread and makes it runnable



This method can be called only once

void run() 



The new thread begins its life inside this method

void stop() (deprecated) 

The thread is being terminated

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

9

Thread States-Life cycle 

Thread states 

Born state



Ready state (runnable state)



Running state



Dead state



Blocked state



Waiting state



Sleeping state

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

10

Thread Lifecycle sleep(500) Active wake up

JV M Born

suspend()

start() Runnable

stop()

resume()

Blocked wait

stop() notify

Dead I/O available Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

block on I/O

Methods in Java 

yield() 

Causes the currently executing thread object to temporarily pause and allow other threads to execute





Allow only threads of the same priority to run

sleep(int m)/sleep(int m,int n) 

The thread sleeps for m milliseconds, plus n nanoseconds

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

12

Multi Thread Example class A extends Thread { public void run(){ for(int i=1;i<=5;i++){ System.out.println("\t From ThreadA: i= "+i); } System.out.println("Exit from A"); } } class B extends Thread { public void run(){ for(int j=1;j<=5;j++){ System.out.println("\t From ThreadB: j= "+j); } System.out.println("Exit from B"); Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

13

}}

Multi Thread Example class C extends Thread { public void run() { for(int k=1;k<=5;k++) { System.out.println("\t From ThreadC: k= "+k); } System.out.println("Exit from C"); }}

class ThreadTest { public static void main(String args[]) { new A().start(); new B().start(); new C().start(); }} Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

14

Output: From ThreadA: i= 1 From ThreadA: i= 2 From ThreadA: i= 3 From ThreadA: i= 4 From ThreadA: i= 5 Exit from A From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4 From ThreadC: k= 5 Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5 Exit from B

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

15

Online Bank: Serving Many Customers and Operations PC client

Internet Bank Server Local Area Network

Bank Database Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

PDA 16

Shared Resources 

If one thread tries to read the data and other thread tries to update the same date, it leads to inconsistent state.



This can be prevented by synchronising access to data.

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

17

Synchronization 

It allows only one thread to execute at a time. Synchronized keyword applies for method level or block level



Takes out a monitor lock on an object 

Exclusive lock for that thread



If lock is currently unavailable, thread will block



For any object, only one thread may execute inside any of that object’s synchronized methods

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

18

Synchronization Example synchronized void call(String msg) { System.out.println(“Synchronized”); try{ Thread.sleep(1000); } catch(InterruptedException e){ System.out.println("Interrupted"); } System.out.print("] \n"); } Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

19

Thread Deadlock 

If two threads are competing for more than one lock



Example: bank transfer between two accounts 

Thread A has a lock on account 1 and wants to lock account 2



Thread B has a lock on account 2 and wants to lock account 1

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

20

Avoiding Deadlock 

No universal solution



Ordered lock acquisition



Encapsulation (“forcing directionality”)



Spawn new threads



Check and back off



Timeout



Minimize or remove synchronization

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

21

Inter Thread Communication 

Sometimes one thread may be interested in the activities of another. Or, one could have a functional dependency on another. 

Reading from a file or over a network?



Waiting for a given thread to return a result.



Polling (Busy Waiting) vs. Notification



BadConsumer Example

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

22

Waiting for notification 

As defined in object, every object has a wait(), notify(), and notifyAll() method. 



These should never be overridden

They can only be called from inside synchronized blocks, and they only effect other threads in synchronized blocks which are synchronized on the same object.

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

23

wait() (cont’d) 

When a thread enters a wait state, it does nothing until it is notified by another thread.



It also gives up it’s lock on the object when wait is called.

public synchronized blog() { wait(); … // do something } Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

24

notify() 

To awaken a thread, a different thread which has a lock on the same object must call notify.



When notify is called, the block that had the lock on the object continues to have it’s lock it releases it. 

Then a thread is awakened from its wait() and can grab the lock and continue processing.

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

25

notifyAll() 

There are two versions - notify() and notifyAll().



Notify is safe only under 2 conditions: 

When only 1 thread is waiting, and thus guaranteed to be awakened.



When multiple threads are waiting on the same condition, and it doesn’t matter which one awakens.



In general, use notifyAll()

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

26

Summary 

Introduction to Threads



Life cycle and its Methods



Synchronization



Deadlock



Avoiding Deadlock



Inter Thread Communication

Nace Solutions (P) Ltd. Copyright © 2008,All Rights Reserved.

27

Related Documents

Java Threads
April 2020 4
Threads Java
November 2019 4
Threads Java Ucv
November 2019 6
Java Threads - Tutorial
November 2019 7

More Documents from ""