threads a thread is a program unit that is executed independently of other parts of the program a...

36
Threads Threads A thread is a program unit that A thread is a program unit that is executed independently of is executed independently of other parts of the program other parts of the program The Java Virtual Machine executes The Java Virtual Machine executes each thread in the program for a each thread in the program for a short amount of time short amount of time This gives the impression of This gives the impression of parallel execution parallel execution

Post on 21-Dec-2015

226 views

Category:

Documents


1 download

TRANSCRIPT

ThreadsThreads A thread is a program unit that is executed A thread is a program unit that is executed

independently of other parts of the program independently of other parts of the program

The Java Virtual Machine executes each The Java Virtual Machine executes each thread in the program for a short amount of thread in the program for a short amount of time time

This gives the impression of parallel This gives the impression of parallel execution execution

Steps to Running a ThreadsSteps to Running a Threads

Implement a class that extends the Implement a class that extends the ThreadThread class class Place the code for your task into the Place the code for your task into the runrun method method

of your class of your class Create an object of your subclass Create an object of your subclass Call the Call the startstart method of your class to start the method of your class to start the

thread thread When a When a ThreadThread object is started, the code in its object is started, the code in its runrun

method is executed in a new threadmethod is executed in a new thread

GreetingThread OutlineGreetingThread Outline

A program to print a time stamp and "Hello World" A program to print a time stamp and "Hello World" once a second for ten seconds once a second for ten seconds

public class GreetingThread extends Thread public class GreetingThread extends Thread

{//variables used by the thread action {//variables used by the thread action

public void run() public void run()

{ {

//thread action //thread action

. . . . . .

} }

. . . . . .

}}

Thread Action for Thread Action for GreetingThreadGreetingThread

Print a time stamp Print a time stamp

Print the greeting Print the greeting

Wait a second Wait a second

GreetingThreadGreetingThread

• We can get the date and time by constructing Date object We can get the date and time by constructing Date object Date now = new Date();Date now = new Date();

• To wait a second, use the sleep method of the Thread To wait a second, use the sleep method of the Thread class class

sleep(milliseconds)sleep(milliseconds)

• A sleeping thread can generate an InterruptedException A sleeping thread can generate an InterruptedException

o Catch the exception Catch the exception

o Terminate the thread Terminate the thread

GreetingThreadGreetingThread runrun methodmethod public run() public run()

{ {

try try

{ {

//thread action //thread action

}}

catch (InterruptedException catch (InterruptedException exception) exception)

{{

//cleanup, if necessary //cleanup, if necessary

} }

} }

File GreetingThread.javaFile GreetingThread.java 01: import java.util.Date;01: import java.util.Date;02: 02: 03: /**03: /**04: A thread that repeatedly prints a greeting.04: A thread that repeatedly prints a greeting.05: */05: */06: public class GreetingThread extends Thread06: public class GreetingThread extends Thread07: { // constants07: { // constants private static final int REPETITIONS = 10;private static final int REPETITIONS = 10; private static final int DELAY = 1000;private static final int DELAY = 1000; //instance variable//instance variable private String greeting;private String greeting;08: /**08: /**09: Constructor.09: Constructor.10: @param aGreeting the greating to display10: @param aGreeting the greating to display11: */11: */12: public GreetingThread(String aGreeting)12: public GreetingThread(String aGreeting)13: {13: {14: greeting = aGreeting;14: greeting = aGreeting;15: }15: }16: 16:

17: public void run()17: public void run()18: {18: {19: try19: try20: {20: {21: for (int i = 1; i <= REPETITIONS; i++)21: for (int i = 1; i <= REPETITIONS; i++)22: {22: {23: Date now = new Date();23: Date now = new Date();24: System.out.println(now + " " + greeting);24: System.out.println(now + " " + greeting);25: sleep(DELAY); 25: sleep(DELAY); 26: }26: }27: }27: }28: catch (InterruptedException exception)28: catch (InterruptedException exception)29: {29: {30: }30: }31: }31: }32:}32:}

To Start the ThreadTo Start the Thread

• Construct an object of your thread classConstruct an object of your thread classGreetingThread t = new GreetingThread t = new

GreetingThread("Hello GreetingThread("Hello World"); World");

• Call the start methodCall the start methodthat belongs to Threadthat belongs to Thread

t.start();t.start();

File GreetingThreadTest.javaFile GreetingThreadTest.java01: import java.util.Date;01: import java.util.Date;02: 02: 03: /**03: /**04: This program tests the greeting thread by running two04: This program tests the greeting thread by running two05: threads in parallel.05: threads in parallel.06: */06: */07: public class GreetingThreadTest07: public class GreetingThreadTest08: {08: {09: public static void main(String[] args)09: public static void main(String[] args)10: {10: {11: GreetingThread t1 = new GreetingThread("Hello, World!");11: GreetingThread t1 = new GreetingThread("Hello, World!");12: GreetingThread t2 = new GreetingThread("Goodbye, World!");12: GreetingThread t2 = new GreetingThread("Goodbye, World!");13: 13: 14: t1.start();14: t1.start();15: t2.start();15: t2.start();16: }16: }17: }17: }

Thread SchedulerThread Scheduler• The thread scheduler runs each thread for a The thread scheduler runs each thread for a

short amount of time called a short amount of time called a time slicetime slice • Then the scheduler picks another thread from Then the scheduler picks another thread from

those that are those that are runnablerunnable • A thread is A thread is runnablerunnable if it is not asleep or if it is not asleep or

blocked in some way blocked in some way • There is no guarantee about the order in which There is no guarantee about the order in which

threads are executed threads are executed

Terminating ThreadsTerminating Threads • A thread terminates when its A thread terminates when its runrun method method

returns returns

• Do not terminate a thread using the Do not terminate a thread using the deprecated deprecated stopstop method method

• Instead, notify a thread that it should Instead, notify a thread that it should terminate terminate

t.interrupt();t.interrupt();

Terminating ThreadsTerminating Threads • A thread's A thread's runrun method should check occasionally method should check occasionally

whether it has been interrupted whether it has been interrupted

o Use the Use the isInterruptedisInterrupted method method

o An interrupted thread should release resources, An interrupted thread should release resources, clean up, and exit clean up, and exit

• The The sleepsleep method throws an InterruptedException method throws an InterruptedException when a sleeping thread is interrupted when a sleeping thread is interrupted

o Catch the exception Catch the exception

o Terminate the thread Terminate the thread

Terminating a ThreadTerminating a Threadpublic void run( public void run(

{ {

try try

{ {

for (int = 1; i <= REPETITIONS for (int = 1; i <= REPETITIONS && !isInterrupted(); i++) && !isInterrupted(); i++)

{ {

//do the work //do the work

} }

}}

catch (InterruptedException exception) catch (InterruptedException exception)

{ { } }

//cleanup //cleanup

} }

Corrupting Data with Corrupting Data with Unsynchronized ThreadsUnsynchronized Threads

• When threads share a common object, When threads share a common object, they can conflict with each other. they can conflict with each other.

• In this example, a In this example, a DepositThreadDepositThread and a and a WithdrawThreadWithdrawThread both manipulate a single both manipulate a single BankAccountBankAccount

runrun Method of Method of DepositThreadDepositThread

public void run()public void run()

{{

trytry

{{

for (int i = 1; i <= REPETITIONS && !for (int i = 1; i <= REPETITIONS && !isInterrupted(); i++)isInterrupted(); i++)

{{

account.deposit(amount);account.deposit(amount);

sleep(DELAY);sleep(DELAY);

}}

}}

catch (InterruptedException exception)catch (InterruptedException exception)

{{

}}

}}

Sample ApplicationSample Application Create a BankAccount object Create a BankAccount object

Create a Create a DepositThread t0DepositThread t0 to deposit $100 into to deposit $100 into the account for 10 iterations the account for 10 iterations

Create a Create a WithdrawThread t1WithdrawThread t1 to withdraw $100 to withdraw $100 from the account for 10 iterations from the account for 10 iterations

The result should be zero, but sometimes it The result should be zero, but sometimes it is notis not

Race conditionRace condition Occurs if the effect of multiple threads on Occurs if the effect of multiple threads on

shared data depends on the order in which shared data depends on the order in which the threads are scheduled the threads are scheduled

It is possible for a thread to reach the end It is possible for a thread to reach the end of its time slice in the middle of a of its time slice in the middle of a statement. statement.

It may evaluate the right-hand side of an It may evaluate the right-hand side of an equation but not be able to store the result equation but not be able to store the result until its next turn. until its next turn.

Solving the Race Condition Solving the Race Condition Problem Problem

• A thread must be able to lock an object A thread must be able to lock an object temporarily temporarily

• When a thread has the object locked, no other When a thread has the object locked, no other thread can modify the state of the object. thread can modify the state of the object.

• In Java, use synchronized methods to do this In Java, use synchronized methods to do this • Tag all methods that contain thread-sensitive code Tag all methods that contain thread-sensitive code

with the keyword with the keyword synchronizedsynchronized

Synchronized MethodsSynchronized Methodspublic class BankAccountpublic class BankAccount

{{

public synchronized void deposit(double amount)public synchronized void deposit(double amount)

{{

. . .. . .

}}

public synchronized void withdraw(double amount)public synchronized void withdraw(double amount)

{{

. . .. . .

}}

. . .. . .

}}

Synchronized MethodsSynchronized Methods• By declaring both the deposit and withdraw By declaring both the deposit and withdraw

methods to be synchronized methods to be synchronized

o Our program will run correctly Our program will run correctly

o Only one thread at a time can execute either Only one thread at a time can execute either method on a given object method on a given object

o When a thread starts one of the methods, it is When a thread starts one of the methods, it is guaranteed to execute the method to completion guaranteed to execute the method to completion before another thread can execute a before another thread can execute a synchronized method on the same object. synchronized method on the same object.

Synchronized MethodsSynchronized Methods

• By executing a synchronized method: By executing a synchronized method:

o The thread acquires the object lock. The thread acquires the object lock.

o No other thread can acquire the lock. No other thread can acquire the lock.

o No other thread can modify the state of the No other thread can modify the state of the object until the first thread is finished object until the first thread is finished

DeadlockDeadlock • A deadlock occurs if no thread can proceed because A deadlock occurs if no thread can proceed because

each thread is waiting for another to do some work each thread is waiting for another to do some work first first

• BankAccount example BankAccount example public synchronized void withdraw(double amount)public synchronized void withdraw(double amount)

{{

while (balance < amount)while (balance < amount)

//wait for balance to grow//wait for balance to grow

. . .. . .

}}

DeadlockDeadlock • The method can lead to deadlock The method can lead to deadlock • The thread sleeps to wait for balance to grow, but it The thread sleeps to wait for balance to grow, but it

still has the lock still has the lock • No other thread can execute the synchronized No other thread can execute the synchronized

deposit method deposit method • If a thread tries to call deposit, it is blocked until the If a thread tries to call deposit, it is blocked until the

withdraw method exits withdraw method exits • withdraw method can't exit until it has funds withdraw method can't exit until it has funds

available available • DEADLOCK DEADLOCK

Avoiding DeadlockAvoiding Deadlock

• The The waitwait method temporarily releases the method temporarily releases the object lock and deactivates the thread object lock and deactivates the thread

withdrawwithdraw Method to Avoid Deadlock Method to Avoid Deadlock

public synchronized void public synchronized void withdraw(double amount)withdraw(double amount)

throws InterruptedExceptionthrows InterruptedException

{{

while (balance < amount)while (balance < amount)

wait();wait();

}}

WaitWait and and NotifyAllNotifyAll • A thread that calls A thread that calls waitwait is in a blocked state is in a blocked state

• It will not be activated by the thread scheduler It will not be activated by the thread scheduler until it is unblocked until it is unblocked

• It is unblocked when another thread calls It is unblocked when another thread calls notifyAllnotifyAll

• When a thread calls When a thread calls notifyAllnotifyAll, all threads , all threads waiting on the object are unblocked waiting on the object are unblocked

• Only the thread that has the lock can call Only the thread that has the lock can call notifyAllnotifyAll

File BankAccountThreadTest.javaFile BankAccountThreadTest.java

Using synchronized methods Using synchronized methods 01: import java.util.Random;01: import java.util.Random;

02: 02:

03: /**03: /**

04: This program runs four threads that deposit and withdraw04: This program runs four threads that deposit and withdraw

05: money from the same bank account. 05: money from the same bank account.

06: */06: */

07: public class BankAccountThreadTest07: public class BankAccountThreadTest

08: {08: {

09: public static void main(String[] args)09: public static void main(String[] args)

10: {10: {

11: BankAccount account = new BankAccount();11: BankAccount account = new BankAccount();12: 12: 13: DepositThread t0 = new DepositThread(account, 100);13: DepositThread t0 = new DepositThread(account, 100);14: WithdrawThread t1 = new WithdrawThread(account, 100);14: WithdrawThread t1 = new WithdrawThread(account, 100);15: DepositThread t2 = new DepositThread(account, 100);15: DepositThread t2 = new DepositThread(account, 100);16: WithdrawThread t3 = new WithdrawThread(account, 100);16: WithdrawThread t3 = new WithdrawThread(account, 100);17: 17: 18: t0.start();18: t0.start();19: t1.start();19: t1.start();20: t2.start();20: t2.start();21: t3.start();21: t3.start();22: }22: }23: }23: }

File BankAccount.javaFile BankAccount.java 01: /**01: /**02: A bank account has a balance that can be changed by 02: A bank account has a balance that can be changed by 03: deposits and withdrawals.03: deposits and withdrawals.04: */04: */05: public class BankAccount05: public class BankAccount06: {06: {07: /**07: /**08: Constructs a bank account with a zero balance08: Constructs a bank account with a zero balance09: */09: */10: public BankAccount()10: public BankAccount()11: {11: {12: balance = 0;12: balance = 0;13: }13: }14: 14: 15: /**15: /**16: Deposits money into the bank account.16: Deposits money into the bank account.17: @param amount the amount to deposit17: @param amount the amount to deposit

18: */18: */19: public synchronized void deposit(double amount)19: public synchronized void deposit(double amount)20: {20: {21: System.out.print("Depositing " + amount);21: System.out.print("Depositing " + amount);22: double newBalance = balance + amount;22: double newBalance = balance + amount;23: System.out.println(", new balance is " + newBalance);23: System.out.println(", new balance is " + newBalance);24: balance = newBalance;24: balance = newBalance;25: notifyAll();25: notifyAll();26: }26: }27: 27: 28: /**28: /**29: Withdraws money from the bank account.29: Withdraws money from the bank account.30: @param amount the amount to withdraw30: @param amount the amount to withdraw31: */31: */32: public synchronized void withdraw(double amount)32: public synchronized void withdraw(double amount)33: throws InterruptedException33: throws InterruptedException34: {34: {35: while (balance < amount)35: while (balance < amount)36: wait();36: wait();37: System.out.print("Withdrawing " + amount);37: System.out.print("Withdrawing " + amount);

38: double newBalance = balance - amount;38: double newBalance = balance - amount;39: System.out.println(", new balance is " + newBalance);39: System.out.println(", new balance is " + newBalance);40: balance = newBalance;40: balance = newBalance;41: }41: }42: 42: 43: /**43: /**44: Gets the current balance of the bank account.44: Gets the current balance of the bank account.45: @return the current balance45: @return the current balance46: */46: */47: public double getBalance()47: public double getBalance()48: {48: {49: return balance;49: return balance;50: }50: }51: 51: 52: private double balance;52: private double balance;53: }53: }

AnimationAnimation Animation shows different objects moving Animation shows different objects moving

or changing as time progresses or changing as time progresses

Thread programming is useful in animation Thread programming is useful in animation

An algorithm animation helps visualize the An algorithm animation helps visualize the steps in the algorithmsteps in the algorithm

Algorithm AnimationAlgorithm Animation • Runs in a separate thread that periodically Runs in a separate thread that periodically

updates an image of the current state of the updates an image of the current state of the algorithm algorithm

• It then pauses so the user can see the It then pauses so the user can see the change change

• After a short time the algorithm thread After a short time the algorithm thread wakes up and runs to the next point of wakes up and runs to the next point of interest interest

• It updates the image again and pauses againIt updates the image again and pauses again

Applet to Provide User InterfaceApplet to Provide User Interface Start the animation with a mousePressed eventStart the animation with a mousePressed event

If an animation is already running, interrupt the If an animation is already running, interrupt the thread to terminate itthread to terminate it

public class SelectionSortApplet extends Appletpublic class SelectionSortApplet extends Applet

{ { private Thread animationprivate Thread animation public SelectionSortApplet()public SelectionSortApplet() {{ class MousePressListener extends MouseAdapterclass MousePressListener extends MouseAdapter {{ public void mousePressed(MouseEvent event)public void mousePressed(MouseEvent event) {{ if (animation != null && if (animation != null &&

animation.isAlive())animation.isAlive()) animation.interrupt();animation.interrupt(); startAnimation();startAnimation(); }}

}}

MouseListener listener = new MousePressListener();MouseListener listener = new MousePressListener();

addMouseListener(listener);addMouseListener(listener);

. . .. . .

animation = null;animation = null;

}}

. . .. . .

}}