Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently."— Presentation transcript:

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

2 Steps to Running a Threads Implement a class that extends the Thread class Implement a class that extends the Thread class Place the code for your task into the run method of your class Place the code for your task into the run method of your class Create an object of your subclass Create an object of your subclass Call the start method of your class to start the thread Call the start method of your class to start the thread When a Thread object is started, the code in its run method is executed in a new thread When a Thread object is started, the code in its run method is executed in a new thread

3 GreetingThread Outline A program to print a time stamp and "Hello World" once a second for ten seconds A program to print a time stamp and "Hello World" 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() { //thread action... }...... }

4 Thread Action for GreetingThread Print a time stamp Print a time stamp Print the greeting Print the greeting Wait a second Wait a second

5 GreetingThread We can get the date and time by constructing Date object Date now = new Date(); We can get the date and time by constructing Date object Date now = new Date(); To wait a second, use the sleep method of the Thread class sleep(milliseconds) To wait a second, use the sleep method of the Thread class sleep(milliseconds) A sleeping thread can generate an InterruptedException A sleeping thread can generate an InterruptedException o Catch the exception o Terminate the thread

6 GreetingThread run method public run() {try{ //thread action } catch (InterruptedException exception) { //cleanup, if necessary }}

7 File GreetingThread.java 01: import java.util.Date; 02: 03: /** 04: A thread that repeatedly prints a greeting. 05: */ 06: public class GreetingThread extends Thread 07: { // 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: /** 09: Constructor. 10: @param aGreeting the greating to display 11: */ 12: public GreetingThread(String aGreeting) 13: { 14: greeting = aGreeting; 15: } 16:

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

9 To Start the Thread Construct an object of your thread class GreetingThread t = new GreetingThread("Hello World"); Construct an object of your thread class GreetingThread t = new GreetingThread("Hello World"); Call the start method that belongs to Thread Call the start method that belongs to Thread t.start(); t.start();

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

11 Thread Scheduler The thread scheduler runs each thread for a short amount of time called a time slice The thread scheduler runs each thread for a short amount of time called a time slice Then the scheduler picks another thread from those that are runnable Then the scheduler picks another thread from those that are runnable A thread is runnable if it is not asleep or blocked in some way A thread is runnable if it is not asleep or blocked in some way There is no guarantee about the order in which threads are executed There is no guarantee about the order in which threads are executed

12 Terminating Threads A thread terminates when its run method returns A thread terminates when its run method returns Do not terminate a thread using the deprecated stop method Do not terminate a thread using the deprecated stop method Instead, notify a thread that it should terminate Instead, notify a thread that it should terminatet.interrupt();

13 Terminating Threads A thread's run method should check occasionally whether it has been interrupted A thread's run method should check occasionally whether it has been interrupted o Use the isInterrupted method o An interrupted thread should release resources, clean up, and exit The sleep method throws an InterruptedException when a sleeping thread is interrupted The sleep method throws an InterruptedException when a sleeping thread is interrupted o Catch the exception o Terminate the thread

14 Terminating a Thread public void run( {try{ for (int = 1; i <= REPETITIONS && !isInterrupted(); i++) { //do the work } } catch (InterruptedException exception) catch (InterruptedException exception) { } { } //cleanup //cleanup}

15 Corrupting Data with Unsynchronized Threads When threads share a common object, they can conflict with each other. When threads share a common object, they can conflict with each other. In this example, a DepositThread and a WithdrawThread both manipulate a single BankAccount In this example, a DepositThread and a WithdrawThread both manipulate a single BankAccount

16 run Method of DepositThread public void run() { try try { for (int i = 1; i <= REPETITIONS && !isInterrupted(); i++) for (int i = 1; i <= REPETITIONS && !isInterrupted(); i++) { account.deposit(amount); account.deposit(amount); sleep(DELAY); sleep(DELAY); } } catch (InterruptedException exception) catch (InterruptedException exception) { } }

17 Sample Application Create a BankAccount object Create a BankAccount object Create a DepositThread t0 to deposit $100 into the account for 10 iterations Create a DepositThread t0 to deposit $100 into the account for 10 iterations Create a WithdrawThread t1 to withdraw $100 from the account for 10 iterations Create a WithdrawThread t1 to withdraw $100 from the account for 10 iterations The result should be zero, but sometimes it is not The result should be zero, but sometimes it is not

18 Race condition Occurs if the effect of multiple threads on shared data depends on the order in which the threads are scheduled Occurs if the effect of multiple threads on shared data depends on the order in which the threads are scheduled It is possible for a thread to reach the end of its time slice in the middle of a statement. It is possible for a thread to reach the end of its time slice in the middle of a statement. It may evaluate the right-hand side of an equation but not be able to store the result until its next turn. It may evaluate the right-hand side of an equation but not be able to store the result until its next turn.

19 Solving the Race Condition Problem A thread must be able to lock an object temporarily A thread must be able to lock an object temporarily When a thread has the object locked, no other thread can modify the state of the object. When a thread has the object locked, no other 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 with the keyword synchronized Tag all methods that contain thread-sensitive code with the keyword synchronized

20 Synchronized Methods public 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) {...... } }

21 Synchronized Methods By declaring both the deposit and withdraw methods to be synchronized By declaring both the deposit and withdraw methods to be synchronized oOur program will run correctly oOnly one thread at a time can execute either method on a given object oWhen a thread starts one of the methods, it is guaranteed to execute the method to completion before another thread can execute a synchronized method on the same object.

22 Synchronized Methods By executing a synchronized method: By executing a synchronized method: oThe thread acquires the object lock. oNo other thread can acquire the lock. oNo other thread can modify the state of the object until the first thread is finished

23 Deadlock A deadlock occurs if no thread can proceed because each thread is waiting for another to do some work first A deadlock occurs if no thread can proceed because each thread is waiting for another to do some work 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...... }

24 Deadlock The method can lead to deadlock The method can lead to deadlock The thread sleeps to wait for balance to grow, but it still has the lock The thread sleeps to wait for balance to grow, but it still has the lock No other thread can execute the synchronized deposit method No other thread can execute the synchronized deposit method If a thread tries to call deposit, it is blocked until the withdraw method exits If a thread tries to call deposit, it is blocked until the withdraw method exits withdraw method can't exit until it has funds available withdraw method can't exit until it has funds available DEADLOCK DEADLOCK

25 Avoiding Deadlock The wait method temporarily releases the object lock and deactivates the thread The wait method temporarily releases the object lock and deactivates the thread

26 withdraw Method to Avoid Deadlock public synchronized void withdraw(double amount) throws InterruptedException throws InterruptedException{ while (balance < amount) while (balance < amount) wait(); wait();}

27 Wait and NotifyAll A thread that calls wait is in a blocked state A thread that calls wait is in a blocked state It will not be activated by the thread scheduler until it is unblocked It will not be activated by the thread scheduler until it is unblocked It is unblocked when another thread calls notifyAll It is unblocked when another thread calls notifyAll When a thread calls notifyAll, all threads waiting on the object are unblocked When a thread calls notifyAll, all threads waiting on the object are unblocked Only the thread that has the lock can call notifyAll Only the thread that has the lock can call notifyAll

28 File BankAccountThreadTest.java Using synchronized methods 01: import java.util.Random; 02: 03: /** 04: This program runs four threads that deposit and withdraw 05: money from the same bank account. 06: */ 07: public class BankAccountThreadTest 08: { 09: public static void main(String[] args) 10: {

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

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

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

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

33 Animation Animation shows different objects moving or changing as time progresses Animation shows different objects moving or changing as time progresses Thread programming is useful in animation Thread programming is useful in animation An algorithm animation helps visualize the steps in the algorithm An algorithm animation helps visualize the steps in the algorithm

34 Algorithm Animation Runs in a separate thread that periodically updates an image of the current state of the algorithmRuns in a separate thread that periodically updates an image of the current state of the algorithm It then pauses so the user can see the changeIt then pauses so the user can see the change After a short time the algorithm thread wakes up and runs to the next point of interestAfter a short time the algorithm thread wakes up and runs to the next point of interest It updates the image again and pauses againIt updates the image again and pauses again

35 Applet to Provide User Interface Start the animation with a mousePressed event If an animation is already running, interrupt the thread to terminate it Start the animation with a mousePressed event If an animation is already running, interrupt the thread to terminate it public class SelectionSortApplet extends Applet { private Thread animation public SelectionSortApplet() public SelectionSortApplet() { class MousePressListener extends MouseAdapter class MousePressListener extends MouseAdapter { public void mousePressed(MouseEvent event) public void mousePressed(MouseEvent event) { if (animation != null && animation.isAlive()) if (animation != null && animation.isAlive()) animation.interrupt(); animation.interrupt(); startAnimation(); startAnimation(); }

36 } MouseListener listener = new MousePressListener(); MouseListener listener = new MousePressListener(); addMouseListener(listener); addMouseListener(listener);...... animation = null; animation = null; }...... }


Download ppt "Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently."

Similar presentations


Ads by Google