Advanced Java Lecture-4,5

55
1 Multithreaded Programming using Java Threads

description

Advanced Java

Transcript of Advanced Java Lecture-4,5

Page 1: Advanced Java Lecture-4,5

1

Multithreaded Programming using Java

Threads

Page 2: Advanced Java Lecture-4,5

2

Web/Internet Applications:Serving Many Users

Simultaneously

Internet Server

PC client

Local Area Network

PDA

Page 3: Advanced Java Lecture-4,5

3

Printing Thread

Editing Thread

Modern Applications need Threads (ex1):Editing and Printing documents in

background.

Page 4: Advanced Java Lecture-4,5

Multithreading is a conceptual programming paradigmwhere a program (process) is divided into two or moresubprograms (processes), which can be implemented atthe same time in parallel.

4

Page 5: Advanced Java Lecture-4,5

A thread is a program that has a single flow of control

It has a beginning, a body, and an end, and executes commands sequentially.

5

Page 6: Advanced Java Lecture-4,5

A unique property of java is its support for multi threading Java enables us to use multiple flows of control in

developing programs Each flow of control may be thought of as a separate tiny

program (or module) known as thread that runs in parallel to others

A program that contains multiple flows of control is known as Multithreaded program

6

Page 7: Advanced Java Lecture-4,5

7

A single threaded program

class ABC{….

public void main(..){…..}

}

beginning

Single-threaded body of execution

end

Page 8: Advanced Java Lecture-4,5

8

A Multithreaded Program

Main Thread

Thread A Thread B Thread C

start startstart

Threads may switch or exchange data/results

Page 9: Advanced Java Lecture-4,5

Contd…..

Java program with 4 threads, one main and three others The main thread is actually the main method module,

which is designed to create and start the other three threads, namely A,B and C

The threads A, B and C run concurrently and share the resources concurrently

The ability of a language to support multithreads is referred to as concurrency

9

Page 10: Advanced Java Lecture-4,5

10

Single and Multithreaded Processes

Single-threaded Process

Single instruction stream Multiple instruction stream

Multiple threaded ProcessThreads ofExecution

CommonAddress Space

threads are light-weight processes within a process

Page 11: Advanced Java Lecture-4,5

Benefits It enables programmers to do multiple things at one

time We can divide a long program (containing operations

that are conceptually concurrent) into threads and execute them in parallel

11

Page 12: Advanced Java Lecture-4,5

Life cycle of a thread Newborn state Runnable state Running state Blocked state Dead state

Page 13: Advanced Java Lecture-4,5

13

Life Cycle of ThreadNewborn

DeadRunnableRunning

start stop

stop

stop

yield Killed Thread

Active Thread

Idle Thread

(Not Runnable)

resume

notify

SuspendSleepwait

Blocked

Page 14: Advanced Java Lecture-4,5

Newborn state When we create a thread object, the thread is born and

is said to be in Newborn state The thread is not yet scheduled for running At this state, we can do only one of the following things

with it: Schedule it for running using start() method Kill it using stop() method

Page 15: Advanced Java Lecture-4,5

Newborn

Runnable state Dead State

start stop

Page 16: Advanced Java Lecture-4,5

Runnable state Means that the thread is ready for execution and is

waiting for the availability of the processor The process of assigning time to threads is known as

TIME-SLICING YIELD

Running Thread

Runnable threads

Relinquishing control using yield() method

Page 17: Advanced Java Lecture-4,5

Running State This means that the processor has

given its time to the thread for its execution

A running thread may relinquish its control in

one of following situations:

Page 18: Advanced Java Lecture-4,5

Suspend

Running suspendedRunnable

resume

After t

Sleep(t)

RunnableRunning sleeping

Page 19: Advanced Java Lecture-4,5

notify

wait

RunnableRunning waiting

Page 20: Advanced Java Lecture-4,5

Blocked state A thread is said to be blocked when

it is prevented from entering into runnable state and subsequently the running state.

Page 21: Advanced Java Lecture-4,5

Blocking a thread A thread can be temporarily suspended or blocked from

entering into the runnable and subsequently running state by using either of the methods:

sleep() // blocked for a specified time suspend() // blocked until further orders wait() // blocked until certain condition occurs

These methods cause the thread to go into the blocked state (or not runnable) state. Sleep() : when specified time is elapsedSuspend(): resume() method is invokedWait(): notify() method is invoked

Page 22: Advanced Java Lecture-4,5

Stopping a thread Whenever we want to stop a thread from running

further, we may do by calling

aThread.stop();

This moves the thread to dead state. The stop method may be used when the prematuredeath of a thread is desired

Page 23: Advanced Java Lecture-4,5

Creating threads Threads are implemented in the form of objects that

contain a method called run()

A typical run() would appear as follows:

public void run(){

………………..……………….. (statements for implementing thread)

}

23

Page 24: Advanced Java Lecture-4,5

A new thread can be created in 2 ways:

By creating a thread class : Define a class that extends thread class and override its run() method with the code required by the thread

By converting a class to a thread: Define a class that implements Runnable interface. The Runnable interfaces has only one method., run(), that is to defined in the method with the code to be executed by the thread

24

Page 25: Advanced Java Lecture-4,5

25

Threading Mechanisms... Create a class that extends the Thread class Create a class that implements the Runnable

interface

Thread

MyThread

Runnable

MyClass

Thread

(objects are threads) (objects with run() body)[a] [b]

Page 26: Advanced Java Lecture-4,5

26

1st method: Extending Thread class

Create a class by extending Thread class and override run() method: class MyThread extends Thread {

public void run() { // thread body of execution } } Create a thread: MyThread thr1 = new MyThread(); Start Execution of threads: thr1.start(); //invokes run() method Create and Execute: new MyThread().start();

Page 27: Advanced Java Lecture-4,5

27

An exampleclass MyThread extends Thread { public void run()

{ for(int i=1;i<=5;i++) {

System.out.println(“ this thread is running:i “ +i); } System.out.println(“exit from A”);

}}

class ThreadEx1 { public static void main (String [] args )

{MyThread t = new MyThread();t.start();

}}

Page 28: Advanced Java Lecture-4,5

28

2nd method: Threads by implementing Runnable interface

Create a class that implements the interface Runnable and override run() method:

class MyThread implements Runnable{ ..... public void run() { // thread body of execution }} Creating Object: MyThread myObject = new MyThread(); Creating Thread Object: Thread thr1 = new Thread(myObject); Start Execution: thr1.start();

Page 29: Advanced Java Lecture-4,5

29

An exampleclass MyThread implements Runnable { public void run()

{ System.out.println(" this thread is running ... "); }}

class ThreadEx2 { public static void main (String [] args )

{ Thread t = new Thread(new MyThread()); t.start(); } }

Page 30: Advanced Java Lecture-4,5

30

A Program with Three Java Threads

Write a program that creates 3 threads

Page 31: Advanced Java Lecture-4,5

31

Three threads exampleclass 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"); }}

Page 32: Advanced Java Lecture-4,5

32

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(); }}

Page 33: Advanced Java Lecture-4,5

33

Run 1Javac ThreadTest.javajava ThreadTest From ThreadA: i= 1 From ThreadA: i= 2 From ThreadA: i= 3 From ThreadA: i= 4 From ThreadA: i= 5Exit from A From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4 From ThreadC: k= 5Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5Exit from B

Page 34: Advanced Java Lecture-4,5

34

Run2[raj@mundroo] threads [1:77] java ThreadTest From ThreadA: i= 1 From ThreadA: i= 2 From ThreadA: i= 3 From ThreadA: i= 4 From ThreadA: i= 5 From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4 From ThreadC: k= 5Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5Exit from BExit from A

Page 35: Advanced Java Lecture-4,5

class A extends Thread{ public void run() {

for(int i=1;i<=5;i++) {

if(i==1) yield(); System.out.println("\t From Thread A: 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 Thread B: j= "+j);if (j==3) stop(); }

System.out.println("Exit from B"); } } 35

Example 2

Page 36: Advanced Java Lecture-4,5

class C extends Thread{

public void run() { for(int k=1;k<=5;k++) {

System.out.println("\t From Thread C: k= “ +k);if (k==1) {

sleep(1000);}

} System.out.println(“Exit from C”);

} }

36

Page 37: Advanced Java Lecture-4,5

class ThreadMethods{

public static void main(String args[]) { A threadA=new A(); B threadB=new B(); C threadC=new C();

System.out.println("Start Thread A"); threadA.start(); System.out.println("Start Thread B"); threadB.start(); System.out.println("Start Thread C"); threadC.start();

System.out.println("End of main thread"); }

}

37

Page 38: Advanced Java Lecture-4,5

Start thread AStart thread BStart thread C

From thread B: j=1From thread B: j=2From thread B: j=3From thread A: i=1From thread A: i=2

End of main threadFrom thread C: k=1From thread A: i=3From thread A: i=4

From thread A: i=5Exit from A

From thread C: k=2 From thread C: k=3 From thread C: k=4 From thread C: k=5

Exit from C

38

Page 39: Advanced Java Lecture-4,5

39

Page 40: Advanced Java Lecture-4,5

Using isAlive() and join()Two ways exist to determine whether a thread has finished. First, you can call isAlive( ) on the thread.

This method is defined by Thread, and its general form is:

final boolean isAlive( )

The isAlive( ) method returns true if the thread upon which it is

called is still running.It returns false otherwise.

40

Page 41: Advanced Java Lecture-4,5

Contd..While isAlive( ) is occasionally useful, the methodthat you will more commonly use to wait for a threadto finish is called join( ), shown here:

final void join( ) throws InterruptedException

This method waits until the thread on which it is calledterminates. Its name comes from the concept of the calling thread

waitinguntil the specified thread joins it.

41

Page 42: Advanced Java Lecture-4,5

42

Thread Priority In Java, each thread is assigned priority, which affects

the order in which it is scheduled for running. The threads so far had same default priority (NORM_PRIORITY) and they are served using FCFS policy. Java allows users to change priority:

ThreadName.setPriority(intNumber) MIN_PRIORITY = 1 NORM_PRIORITY=5 MAX_PRIORITY=10

Page 43: Advanced Java Lecture-4,5

43

Thread Priority Exampleclass A extends Thread{ public void run() { System.out.println("Thread A started"); for(int i=1;i<=4;i++) { System.out.println("\t From ThreadA: i= "+i); } System.out.println("Exit from A"); }}class B extends Thread{ public void run() { System.out.println("Thread B started"); for(int j=1;j<=4;j++) { System.out.println("\t From ThreadB: j= "+j); } System.out.println("Exit from B"); } }

Page 44: Advanced Java Lecture-4,5

44

Thread Priority Exampleclass C extends Thread{ public void run() { System.out.println("Thread C started"); for(int k=1;k<=4;k++) { System.out.println("\t From ThreadC: k= "+k); } System.out.println("Exit from C"); } }class ThreadPriority{ public static void main(String args[]) { A threadA=new A(); B threadB=new B(); C threadC=new C(); threadC.setPriority(Thread.MAX_PRIORITY); threadB.setPriority(threadA.getPriority()+1); threadA.setPriority(Thread.MIN_PRIORITY); System.out.println("Started Thread A"); threadA.start(); System.out.println("Started Thread B"); threadB.start(); System.out.println("Started Thread C"); threadC.start(); System.out.println("End of main thread"); } }

Page 45: Advanced Java Lecture-4,5

45

Run 1Start thread AStart thread BStart thread CthreadB started

From ThreadB: j= 1 From ThreadB: j= 2threadC started From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4Exit from CEnd of main thread From ThreadB: j= 3 From ThreadB: j= 4Exit from BthreadA started

From ThreadA: i= 1 From ThreadA: i= 2 From ThreadA: i= 2 From ThreadA: i= 2Exit from A

Page 46: Advanced Java Lecture-4,5

46

Accessing Shared Resources Applications Access to Shared Resources

need to be coordinated. Printer (two person jobs cannot be printed at

the same time) Simultaneous operations on your bank account. Can the following operations be done at the

same time on the same account? Deposit() Withdraw() Enquire()

Page 47: Advanced Java Lecture-4,5

47

Online Bank: Serving Many Customers and Operations

Internet Bank Server

PC client

Local Area Network

PDABank

Database

Page 48: Advanced Java Lecture-4,5

class Callme {void call(String msg) {

System.out.print("[" + msg);try {Thread.sleep(1000);} catch(InterruptedException e) {System.out.println("Interrupted");}System.out.println("]");

}}

class Caller implements Runnable{

String msg;Callme target;Thread t;public Caller(Callme targ, String s) {target = targ;msg = s;t = new Thread(this);t.start();}public void run() {target.call(msg);}

}

48

Page 49: Advanced Java Lecture-4,5

class Synch {public static void main(String args[]) {Callme target = new Callme();Caller ob1 = new Caller(target, "Hello");Caller ob2 = new Caller(target, "Synchronized");Caller ob3 = new Caller(target, "World");// wait for threads to endtry {ob1.t.join();ob2.t.join();ob3.t.join();} catch(InterruptedException e) {System.out.println("Interrupted");}}}

49

Page 50: Advanced Java Lecture-4,5

Here is the output produced by this program:Hello[Synchronized[World]]]

50

Page 51: Advanced Java Lecture-4,5

Solution 1class Callme {synchronized void call(String msg) {...}}After synchronized has been added to call( ), theoutput of the program is as follows:[Hello][Synchronized][World]

51

Page 52: Advanced Java Lecture-4,5

Solution 2put calls to the methods defined by this class inside a

synchronizedblock.This is the general form of the synchronized statement:synchronized(object) {// statements to be synchronized}Here, object is a reference to the object being synchronized. Asynchronized block ensures that a call to a method that is a

memberof object occurs only after the current thread has successfullyentered object’s monitor.

52

Page 53: Advanced Java Lecture-4,5

class Callme {void call(String msg) {

System.out.print("[" + msg);try {Thread.sleep(1000);} catch(InterruptedException e) {System.out.println("Interrupted");}System.out.println("]");

}}

class Caller implements Runnable{

String msg;Callme target;Thread t;public Caller(Callme targ, String s) {target = targ;msg = s;t = new Thread(this);t.start();}public void run() {

synchronized(target) {target.call(msg); }}

}

53

Page 54: Advanced Java Lecture-4,5

class Synch {public static void main(String args[]) {Callme target = new Callme();Caller ob1 = new Caller(target, "Hello");Caller ob2 = new Caller(target, "Synchronized");Caller ob3 = new Caller(target, "World");// wait for threads to endtry {ob1.t.join();ob2.t.join();ob3.t.join();} catch(InterruptedException e) {System.out.println("Interrupted");}}}

54

Page 55: Advanced Java Lecture-4,5

Comparison

55