java threads dev

31
 Ja va Threads

Upload: indra668

Post on 07-Apr-2018

246 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 1/31

 Java Threads

Page 2: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 2/31

y What is a Thread?

Why threads? ² Need to handle concurrent processes--Definition

 ² Single sequential flow of control within a program ² For simplicity, think of threads as processes

executed by a program

 ² Example:Operating SystemHotJava web browser

Page 3: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 3/31

MultiMulti--threading in Javathreading in Java

PlatformPlatformEvery application has at least one thread ³ 

or several, if you count "system" threadsthat do things like memory management

and signal handling

But from the application programmer'spoint of view, you start with just one

thread, called the main thread. This threadhas the ability to create additional threads

Page 4: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 4/31

Life Cycle Of a ThreadLife Cycle Of a Thread

Page 5: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 5/31

Page 6: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 6/31

y NEWA thread that has not yet started is in this state.

y RUNNABLEA thread executing in the Java virtual machine is in this state.

y BLOCKED

A thread that is blocked waiting for a monitor lock is in thisstate.

y WAITINGA thread that is waiting indefinitely for another thread toperform a particular action is in this state.

y TIMED_WAITINGA thread that is waiting for another thread to perform anaction for up to a specified waiting time is in this state.

y TERMINATEDA thread that has exited is in this state.

Page 7: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 7/31

Methods that can be applied apply on aMethods that can be applied apply on a

ThreadThread

Method Return Type Description

currentThread( ) Thread

Returns an object

reference to the thread

in which it is invoked.

getName( ) StringRetrieve the name of the thread object or 

instance.

start( ) voidStart the thread by

calling its run method.

run( ) void

This method is theentry point to execute

thread, like the main

method for applications.

sleep( ) void

Suspends a thread for 

a specified amount of time (in milliseconds).

Page 8: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 8/31

isAlive( ) boolean

 

determine the thread is

running or not.

activeCount( ) int

This method returns the

number of active threads

in a particular thread groupand all its subgroups.

interrupt( ) void

The method interrupt the

threads on which it is

invoked.

yield( ) void

By invoking this method

the current thread pauseits execution temporarily

and allow other threads to

execute.

  join( ) void

This method

and  join(long millisec)

Throws

InterruptedException. The

se two methods are

invoked on a thread.

These are not returned

until either the thread has

completed or it is timed outrespectively.

Page 9: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 9/31

Thread PrioritiesThread Priorities

Why priorities?

 ² Determine which thread receives CPU control and gets

to be executed first

Definition:

 ² Integer value ranging from 1 to 10 ² Higher the thread priority larger chance of being

executed first

 ² Example:

Two threads are ready to run

First thread: priority of 5, already running Second thread = priority of 10, comes in while first thread

is running

Page 10: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 10/31

Thread PrioritiesThread Priorities

Context switch

 ² Occurs when a thread snatches the control of CPU from

another

 ² When does it occur?

Running thread voluntarily relinquishes CPU control Running thread is preempted by a higher priority thread

More than one highest priority thread that is ready

to run

 ² Deciding which receives CPU control depends on the

operating system ² Windows 95/98/NT: Uses time-sliced round-robin

 ² Solaris: Executing thread should voluntarily relinquish

CPU control

Page 11: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 11/31

Two Ways of CreatingTwo Ways of Creating

 Java Threads Java Threads1.Extending the Thread class

2.Implementing the Runnable interface

Page 12: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 12/31

Extending ThreadExtending Thread

ClassClassThe subclass extends Thread class

 ²The subclass overrides the run() method of Thread class

A

n object instance of the subclass can then becreated

Calling the start() method of the object instance

starts the execution of the thread

 ² Java runtime starts the execution of the thread bycalling run() method of object instance

Page 13: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 13/31

Two Schemes of starting aTwo Schemes of starting a

thread from a subclassthread from a subclassThe start() method is not in the constructor of the

subclass

 ² The start() method needs to be explicitly

invoked after object instance of the subclassis created in order to start the thread

2.The start() method is in the constructor of the

subclass

 ² Creating an object instance of the subclasswill start the

thread

Page 14: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 14/31

start() method needs tostart() method needs to

be called ex

plicitlybe called ex

plicitly1 class PrintNameThread extends Thread {

2 PrintNameThread(String name) {

3 super(name);

4 }

5 public void run() {6 String name = getName();

7 for (int i = 0; i < 100; i++) {

8 System.out.print(name);

9 }10 }

11 }

12 //continued

Page 15: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 15/31

14class ExtendThreadClassTest1 {15 public static void main(String args[]) {16 PrintNameThread pnt1 =

17 new PrintNameThread("A

");18 pnt1.start(); // Start the first thread19 PrintNameThread pnt2 =20 new PrintNameThread("B");

21 pnt2.start(); // Start the second thread2223 }

Page 16: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 16/31

 Just creating an object Just creating an object

instance starts a threadinstance starts a thread1 class PrintNameThread extends Thread {

2 PrintNameThread(String name) {

3 super(name);

4 start(); //runs the thread once instantiated

5 }6 public void run() {

7 String name = getName();

8 for (int i = 0; i < 100; i++) {

9 System.out.print(name);

10 }11 }

12 }

13 //continued

Page 17: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 17/31

14 class ExtendThreadClassTest2 {

15 public static void main(String args[]) {

16 PrintNameThread pnt1 =

17 new PrintNameThread("A");18 PrintNameThread pnt2 =

19 new PrintNameThread("B");

2021 }

22 }

Page 18: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 18/31

ImplementingImplementing

RunnableRunnable InterfaceInterfaceThe Runnable interface should be implemented by 

any class whose instances are intended to be

executed as a thread

The class must define run() method of no

arguments ² The run() method is like main() for the new thread

Provides the means for a class to be active while

not subclassing Thread 

 ² A

class that implements Runnable can run withoutsubclassing Thread by instantiating a Thread instance

and passing itself in as the target

Page 19: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 19/31

// PrintNameRunnable implements Runnable interface

class PrintNameRunnable implements Runnable {

String name;

PrintNameRunnable(String name) {

this.name = name;}

// Implementation of the run() defined in the

// Runnable interface.

public void run() {

for (int i = 0; i < 10; i++) {System.out.print(name);

}

}

Page 20: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 20/31

y public class RunnableThreadTest1 {

y public static void main(String args[]) {

y PrintNameRunnable pnt1 = new

PrintNameRunnable("A");

y Thread t1 = new Thread(pnt1);

y t1.start();

y }

y }

Page 21: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 21/31

Extending Thread ClassExtending Thread Class

vs. Implementingvs. Implementing

RunnableRunnableInterfaceInterface

Choosing between these two is a matter of taste

Implementing the Runnable interface

 ² May take more work since we still Declare a Thread object

Call the Thread methods on this object

 ²Your class can still extend other class

Extending the Thread class ² Easier to implement ²Your class can no longer extend any other

class

Page 22: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 22/31

SynchronizationSynchronization

Race conditions occur when multiple,

asynchronously executing threads access the same

object (called a shared resource) returning

unexpected (wrong) results Example:

 ² Threads often need to share a common resourceie a file, with one thread reading from the file

while another thread writes to the fileThey can be avoided by synchronizing the threads

which access the shared resource

Page 23: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 23/31

1class TwoStrings {2 static void print(String str1, String str2) {3 System.out.print(str1);4 try {

5 Thread.sleep(500);6 } catch (InterruptedException ie) {7 }8 System.out.println(str2);

9 }10 }11 //continued...

Page 24: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 24/31

class PrintStringsThread implements Runnable {

13 Thread thread;

14 String str1, str2;

15 PrintStringsThread(String str1, String str2) {

16 this.str1 = str1;

17 this.str2 = str2;18 thread = new Thread(this);

19 thread.start();

20 }

21 public void run() {

22 TwoStrings.print(str1, str2);23 }

24 }

25 //continued...

Page 25: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 25/31

26 class TestThread {

27 public static void main(String args[]) {

28 new PrintStringsThread("Hello ", "there.");

29 new PrintStringsThread("How are ",

"you?");

30 new PrintStringsThread("Thank you ",

31 "very much!");32 }

33 }

Page 26: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 26/31

Sample output:

Hello How are Thank you there.

you?

very much!

Page 27: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 27/31

Synchronization:Synchronization:

Locking an ObjectLocking an ObjectA thread is synchronized by becoming an

owner of the object's monitor

 ² Consider it as locking an objectA thread becomes the owner of the object's

monitorin one of three ways

 ² Option 1: Use synchronized method 

 ² Option 2: Use synchronized statement on acommon

object

Page 28: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 28/31

Use synchronized methodUse synchronized method

1 class TwoStrings {

2 synchronized static void print(String str1,

3 String str2) {

4 System.out.print(str1);

5 try {6 Thread.sleep(500);

7 } catch (InterruptedException ie) {

8 }

9 System.out.println(str2);10 }

11 }

12 //continued...

Page 29: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 29/31

13 class PrintStringsThread implements Runnable {

14 Thread thread;

15 String str1, str2;

16 PrintStringsThread(String str1, String str2) {

17 this.str1 = str1;

18 this.str2 = str2;19 thread = new Thread(this);

20 thread.start();

21 }

22 public void run() {

23 TwoStrings.print(str1, str2);24 }

25 }

26 //continued...

Page 30: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 30/31

27 class TestThread {

28 public static void main(String args[]) {

29 new PrintStringsThread("Hello ", "there.");

30 new PrintStringsThread("How are ",

"you?");

31 new PrintStringsThread("Thank you ",

32 "very much!");33 }

34 }

Page 31: Java Threads Dev

8/6/2019 Java Threads Dev

http://slidepdf.com/reader/full/java-threads-dev 31/31

Sample output:

Hello there.

How are you?

Thank you very much!