threads in java. 2 7.0 threads introduction: after completing this chapter, you will be able to code...

27
Threads in Java Threads in Java

Upload: coleen-davidson

Post on 18-Jan-2018

234 views

Category:

Documents


0 download

DESCRIPTION

3 Interrupted Exception and Thread Priority Controlling Group of Threads and Synchronizing Multiple Threads Single Threaded Execution Optimistic Single Threaded Execution Locking an Object Deadlock and volatile keyword 7.0 Threads

TRANSCRIPT

Page 1: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

Threads in JavaThreads in Java

Page 2: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

2

7.0 Threads

Introduction: After completing this chapter, you will be able to code your own thread, control

them efficiently without any difficulty.Objective:

After completing this chapter you will able to know, Introduction

• What is a Thread• Where to use Threads• Where to use Single Threads

Associating a method with Thread• Declare a subclass of Thread that defines the run() method • Pass a reference to an object that implements the Runnable interface to a Thread

constructor

Starting a ThreadControlling a Thread

Page 3: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

3

Interrupted Exception and Thread PriorityControlling Group of Threads and Synchronizing Multiple ThreadsSingle Threaded ExecutionOptimistic Single Threaded ExecutionLocking an ObjectDeadlock and volatile keyword

7.0 Threads

Page 4: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

4

Introduction

• What is a Thread ?• Flow of Control in a Program • Similar to a process but multiple threads can share same state.• All threads in an application run in the same address space.• Share all resources except Stack.

– In Java “thread” means two different things :• An Instance of java.lang.Thread

– An Instance of Thread is an Object - similar to any other object in java• A Thread of execution

– Is an individual process that has its own call stack

Page 5: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

5

Introduction

• Where to use Threads ?• Where there is a need to engage multiple activities and still be

able to respond to additional input from the user. E.g.: A web browser should be able to respond to user input while fetching an image or playing a sound.

• Where to use Single Threads?• Programs that requires sequential logic

Page 6: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

6

Associating a method with a Thread

• Java provides two ways of associating a method with a Thread :• Declare a subclass of Thread that defines the run() method.• Pass a reference to an object that implements the Runnable interface to a Thread

constructor.

• Declare a subclass of Thread that defines the run() method :

• Subclassing - convenient when the method you want to run in a thread does not need to belong to a particular class.

• E.g. : If you need to load the contents of a URL as part of an applet’s initialization,but the applet can provide other functionality before the content is loaded, you might want to load the content in a separate thread. The class that does it is :

Page 7: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

7

Associating a method with a Thread

E.g :class UrlData extends Thread { private Object data; private URL url; public UrlData(String urlName)throws MalformedURLException {

url = new URL(urlName); start();

} public void run() { try {

data = url.getContent(); } catch (java.io.IOException e) { }

} public Object getUrlData(){

return data; }

}

Page 8: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

8

Associating a method with a Thread• Pass a reference to an object that implements the Runnable interface to a Thread

constructor :

– The method that you want to run in a thread to be a part of a particular class that is a subclass of a class other than thread, then use the runnable interface.

E.g.: class AutoColor extends java.awt.Canvas implements Runnable { private Thread myThread; AutoColorChange ()

{ myThread = new Thread(this);

myThread.start(); ... }

public void run() {. . .

}}

Page 9: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

9

Starting a Thread

main

Method1main

run

public static void main(String args[]) {

//running

//some code

//in main()

method1();

//running

//more code

}

void method1() {

Runnable r = new Runnable();

Thread t = new Thread();

t.start();

//do more stuff

}

method1main

1) main() begins

2) main() invokes method1()

3) method1() starts a new thread

Stack A

Stack A

Stack A Stack B

Page 10: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

10

Controlling a Thread

• Starting a Thread – use the start() method.

• isAlive() method of the Thread Object – always returns false before starting a thread.

• After start() method has returned – isAlive() method always returns true.

note : On a multi processor system the start() method can even return at the same time the started thread begins to run.

• Thread Objects have parent child relationship.

• A Thread dies when one of the following things happens:• The run() method called by Thread returns.• An Exception is thrown that causes the run() method to be exited.• The stop() method of the thread is called.

Page 11: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

11

Controlling a Thread

New Runnable Running Dead

Waiting/Blocking

TRANSITION BETWEEN THREAD STATES

Page 12: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

12

Interrupted Exception and Thread Priority• Interrupted Exception :

• Methods in Java API such as wait(), join() » throws an Interrupted Exception.» These methods temporarily suspend the execution of a thread.

• Thread Priority :

• getPriority() – helps to query the priority of the a Thread Object• setPriority() – helps to set the priority of a Thread.• Priorities are set using positive integers – usually between 1 to 10 ( however

they’re not guaranteed)• Default Priority – 5

• Thread class has 3 constants that define the range of priorities :

Thread.MIN_PRIORITY (1)Thread.NORM_PRIORITY (5)Thread.MAX_PRIORITY (10)

Note : It is possible for the current priority of the Thread to be greater than the maximum allowable priority for the Thread Group.

Page 13: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

13

Controlling Group of Threads & Synchronizing Multiple Threads

• ThreadGroup class:

– Every Thread object belongs to the ThreadGroup object.

• Synchronizing Multiple Threads :

– Correct behavior of a multi threaded program generally depends on multiple threads cooperating with each other – achieved through synchronization.

– Simplest strategy for ensuring that threads are correctly synchronized :

• Write a code that works correctly when executed concurrently by any number of threads.

Page 14: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

14

Single Threaded Execution

E.g.: class CountIt {

int i = 0; void count() {

i = i + 1; }

} In the above method if 2 threads A and B, calls count in the same time then the problem arises.

Modified program :class CountIt {

int i = 0; synchronized void count() { i = i + 1; }

} So by making the method synchronized, avoids the problem in the former code.

Page 15: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

15

Single Threaded Execution

• The strategy of single threaded execution can also be used when multiple method update the same data.

• E.g.: class CountIt2 {

int i = 0; void count() {

i = i + 1; }

void count2() { i = i + 2;

}

} – In the above example the result could be to increment i by 1,2 or 3.– To avert the problem with the above code - declare both methods as synchronized.

Page 16: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

16

Single Threaded Execution

• By just making a method synchronized does not provide the needed single threaded execution in situations like: – When an inner class is updating fields in its enclosing instance.

E.g.: public class Z extends Frame {

int pressCount = 0; ... private class CountButton extends Button implements Action Listener { public void actionPerformed(ActionEvent evt) {

pressCount ++; } } ...}

Page 17: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

17

Single Threaded Execution

• In this former case – By just declaring the actionPerformed() method as synchronized only forces

the method to acquire lock on the instance of CountButton it is associated with it.

– But the needed is to acquire a lock for is the enclosing instance of Z.

• Robust approach is to have the inner class update a field in its enclosing instance by calling a synchronized method in the enclosing instance

Page 18: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

18

Single Threaded Execution

public class Z extends Frame { int pressCount = 0; synchronized incrementPressCount() { pressCount++; }

... private class CountButton extends Button implements

ActionListener { public void actionPerformed(ActionEvent evt) { incrementPressCount();

} } ...

}

Page 19: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

19

Optimistic Single Threaded Execution

• Similar to Single Threaded Execution strategy.

• Both of them :– begins by getting a lock on an object.– Ends by releasing the lock on that object.– The Difference happens in between :

• If a piece of code discovers that conditions are not right to proceed, the code releases the lock it has on the object and waits.

• After another piece of code makes things right, it notifies the first piece of code to proceed.

• The first piece of code now try to regain its lock on the object and continue.

• To implement this the Object class provides the following methods:

wait()Notify()notifyAll()

Page 20: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

20

Optimistic Single Threaded Execution

• Consider the following example : – It shows how to implement a queue that uses optimistic single threaded

execution strategy.

• E.g :public class Queue extends java.util.Vector {

synchronized public void put(Object obj) { addElement(obj); notify();

}synchronized public Object get() throws EmptyQueueException {

while (size() == 0) wait(); Object obj = elementAt(0); removeElementAt(0); return obj;

}}

Page 21: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

21

Locking an Object • critical sections :

– Code segments that access the same object from separate concurrent threads.• Example :

public class CubbyHole { private int contents;

private boolean available = false; public synchronized int get() {

... } public synchronized void put(int value) { ... }}

– In the above example :• Both methods put() and get() has synchronized keyword.• If the control enters a synchronized method :

– method locks the object and now other threads will not be able to call any other method in same the object, until the object is unlocked.

– The acquisition and release of lock is done automatically by the JVM.

Page 22: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

22

Locking an Object

• Reacquiring a lock :– Java locks are reentrant.– Reentrant locks – eliminates the possibility of a single thread deadlocking itself on

a lock that it already holds.• E.g.: public class Reentrant {

public synchronized void a() {b();System.out.println("here I am, in a()");

} public synchronized void b() {

System.out.println("here I am, in b()"); }

} • On calling method a() the Output is : here I am, in b()

here I am, in a() – The above output was possible as java supports reentrant locks.– Suppose if reentrant locks were not supported, this code would have caused a

deadlock state.

Page 23: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

23

Locking an Object Using the notifyAll and wait methods:

E.g :public synchronized int get() {

while (available == false) { try { // wait for Producer to put value wait(); } catch (InterruptedException e) { } } available = false; // notify Producer that value has been retrieved notifyAll(); return contents;} public synchronized void put(int value) { while (available == true) { try { // wait for Consumer to get value wait(); } catch (InterruptedException e) { } } contents = value; available = true; // notify Consumer that value has been set notifyAll();

}

Page 24: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

24

Deadlock and Volatile Keyword

• Deadlock :– Occurs when two threads are blocked, each waiting for the other’s lock.

• Volatile Keyword :

– Informs the compiler that several threads may be accessing this simultaneously.

Page 25: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

25

Threads - Summary

• Java is fundamentally multi-threaded.• Every thread corresponds to an instance of java.lang.Thread class or a sub-class.• A thread becomes eligible to run, when its start() method is called. Thread scheduler co-

ordinates• between the threads and allows them to run.• When a thread begins execution, the scheduler calls its run method.• Signature of run method – public void run()• When a thread returns from its run method (or stop method is called – deprecated in 1.2),

its dead. It cannot be restarted, but its methods can be called. (it’s just an object no more in a running state)

• There are two ways to implement threads.• 1. Extend Thread class• 2. Implement Runnable interface

• Threads have priorities. Thread class have constants MAX_PRIORITY (10),MIN_PRIORITY (1),NORM_PRIORITY (5)

Page 26: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

26

Threads - Summary

• Every object has a lock (for every synchronized code block). At any moment, this lock is controlled by at most one thread.

• A thread that wants to execute an object’s synchronized code must acquire the lock of the object.If it cannot acquire the lock, the thread goes into blocked state and comes to ready only when the object’s lock is available.

• When a thread, which owns a lock, finishes executing the synchronized code, it gives up the lock.

• 2 ways to synchronize:– Synchronize the entire method– Synchronize part of the method

Page 27: Threads in Java. 2 7.0 Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without

27

Test Your Understanding

• What is a Thread?

• What for is a Thread used?

• What is Multi-Threading?

• What is a lock on object?

• What for is an object locked by a thread?