Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 501N Fall ‘09 21: Introduction to Multithreading

Similar presentations


Presentation on theme: "CSE 501N Fall ‘09 21: Introduction to Multithreading"— Presentation transcript:

1 CSE 501N Fall ‘09 21: Introduction to Multithreading
19 November 2009 Nick Leidenfrost

2 Lecture Outline Lab 8 questions? Threads Multithreading
Race conditions

3 Threads A thread is a unit of execution in Java (and other languages…)
Threads are executed independently of one another However, they may share resources (Objects in your program) Threads execute simultaneously* *The Java Virtual Machine executes each thread in the program for a short amount of time This gives the impression of parallel execution

4 Threads Programs we have written so far are Single-Threaded
Java creates the Main Thread for us when we start our programs We will learn how to create additional threads “Multi-Threading” / Multi-Threaded Programs Exception in thread "main" java.lang.NullPointerException at OutOfBounds.doSomethingBad(OutOfBounds.java:25) at OutOfBounds.<init>(OutOfBounds.java:21) at OutOfBounds.main(OutOfBounds.java:10)

5 Why Use Multiple Threads?
If we want to monitor something continuously Incoming Data More consistent user interaction We can execute statements and accept rich user input (key presses, mouse events) at the same time Our program doesn’t appear to stall if we start a resource intensive task Writing a large amount of data to a stream A large file to disk A large amount of data sent across the net Simultaneous Execution When multiple processors exist (with proper JVM) Simulated for single processor machines Like all design decisions, the choice to use multiple threads depends on your program goals

6 Creating Threads Threads can be created in one of two ways:
By extending the java.lang.Thread class By implementing the java.lang.Runnable interface and passing our Runnable into a Thread

7 Running a Thread Implement a class that implements the Runnable interface public interface Runnable { void run(); }

8 Running a Thread Place the code for your task into the run method of your class public class MyRunnable implements Runnable { public void run () { // Task statements go here } }

9 Running a Thread Create an object of your subclass
Construct a Thread object from the Runnable object. Call the start method to start the thread. Runnable r = new MyRunnable(); Thread t = new Thread(r); t.start();

10 Starting a Thread To start a Thread, we MUST call it’s start() method
We SHOULD NOT call run() directly Also, a thread is not started on creation start will create a new thread of execution and then call run() for us MyThread thread = new MyThread(); Thread.start(); //... More statements ... // Inside MyThread public void run () { while (!interrupted()) { // ... }

11 Starting a Thread If we just call run() on the new Thread, the current thread’s thread of execution will execute the statements in run MyThread thread = new MyThread(); Thread.run(); //... Not executed until ‘run’ // terminates ... // Inside MyThread public void run () { while (!interrupted()) { // ... }

12 Example A program to print a time stamp and "Hello World" once a second for ten seconds: Thu Dec 28 23:12:03 PST 2004 Hello, World! Thu Dec 28 23:12:04 PST 2004 Hello, World! Thu Dec 28 23:12:05 PST 2004 Hello, World! Thu Dec 28 23:12:06 PST 2004 Hello, World! Thu Dec 28 23:12:07 PST 2004 Hello, World! Thu Dec 28 23:12:08 PST 2004 Hello, World! Thu Dec 28 23:12:09 PST 2004 Hello, World! Thu Dec 28 23:12:10 PST 2004 Hello, World! Thu Dec 28 23:12:11 PST 2004 Hello, World! Thu Dec 28 23:12:12 PST 2004 Hello, World!

13 GreetingRunnable Outline
public class GreetingRunnable implements Runnable { // Fields used by the task statements private String greeting; public GreetingRunnable(String aGreeting) { greeting = aGreeting; } public void run() { // Task statements go here }

14 Thread Action for GreetingRunnable
We want to: Print a time stamp Print the greeting Wait a second We can get the date and time by constructing a Date object Date now = new Date();

15 Thread Action for GreetingRunnable
To wait a second, use the sleep method of the Thread class A sleeping thread can generate an InterruptedException Catch the exception Terminate the thread sleep(milliseconds)

16 Running Threads sleep puts current thread to sleep for given number of milliseconds When a thread is interrupted, most common response is to terminate run (We’ll come back to interruptions in a bit) Thread.sleep(milliseconds)

17 Generic run Method public void run() {
try { // Task statements } catch (InterruptedException exception) { } // Clean up, if necessary }

18 GreetingRunnable.java // Code Example

19 Java Thread Scheduler The thread scheduler runs each thread for a short amount of time (a time slice) Then the scheduler activates another thread There will always be slight variations in running times especially when calling operating system services (e.g. input and output) There is no guarantee about the order in which threads are executed

20 Terminating Threads A thread terminates when its run method terminates
Do not terminate a thread using the deprecated stop method Instead, notify a thread that it should terminate interrupt does not cause the thread to terminate–it sets a boolean field in the Thread data structure t.interrupt();

21 Terminating Threads The run method should check occasionally whether it has been interrupted Use the interrupted method An interrupted thread should release resources, clean up, and exit public void run() { int i = 0; while (i <= REPETITIONS && !Thread.interrupted()) { // Do work i++; } // Clean up }

22 Terminating Threads The sleep method throws an InterruptedException when a sleeping thread is interrupted Catch the exception Terminate the thread

23 Terminating Threads Java does not force a thread to terminate when it is interrupted It is entirely up to the thread what it does when it is interrupted Interrupting is a general mechanism for getting the thread's attention

24 Swing Event Thread When we open a window with Swing, Swing provides us a Thread to handle events You have been writing multi-threaded programs without knowing it! // Code example (Don’t worry about altering any of your Lab 8 code for thread interaction – we will do this in later labs)

25 Sample Application Create a BankAccount object Create two threads:
t1 deposits $100 into the bank account for 10 iterations t2 withdraws $100 from the bank account for 10 iterations

26 Sample Application Monitor balance by modifying deposit and withdraw to print messages: // Code Example public void deposit(double amount) { System.out.print("Depositing " + amount); double newBalance = balance + amount; System.out.println(", new balance is " + newBalance); balance = newBalance; }

27 Sample Application Normally, the program output looks somewhat like this: The result should be zero when the program terminates, but sometimes it is not… Depositing 100.0, new balance is Withdrawing 100.0, new balance is 0.0 Depositing 100.0, new balance is Depositing 100.0, new balance is Withdrawing 100.0, new balance is Withdrawing 100.0, new balance is 0.0

28 Sample Application Sometimes, you may notice messed-up output, like this: Depositing 100.0Withdrawing 100.0, new balance is 100.0, new balance is

29 Race Conditions When threads share common resources, they can conflict with each other Sample program: multiple threads manipulate a common BankAccount object

30 Race Conditions Here is the run method of DepositRunnable:
… the WithdrawRunnable class is similar public void run() { try { for (int i = 1; i <= count; i++) { account.deposit(amount); Thread.sleep(DELAY); } } catch (InterruptedException exception) { } }

31 Scenario to explain Non-zero Result: Race Condition
The first thread t1 executes the following lines The balance field is still 0, and the newBalance local variable is 100 t1 reaches the end of its time slice and thread t2 gains control System.out.print("Depositing " + amount); double newBalance = balance + amount;

32 Scenario to explain Non-zero Result: Race Condition
t2 calls the withdraw method which withdraws $100 from the balance, making it -100 t2 goes to sleep T1 regains control and picks up where it left off – it executes: The balance is now 100 instead of 0 because the deposit method has the OLD value for balance System.out.println(", new balance is " + newBalance); balance = newBalance;

33 Corrupting the balance Field
Thread 1 Thread 2 newBalance is 100, balance is still 0 System.out(“Depositing…”) newBalance = balance + amount; System.out(“Withdrawing...”) At this point, t1 reaches the end of its time slice newBalance = balance - amount; System.out(“The new balan...”) balance = newBalance; System.out(“The new balan...”) balance is set to -100 t2 goes to sleep, its time slice ends balance is set to 100, the value of newBalance balance = newBalance;

34 Race Condition Occurs if the effect of multiple threads on shared data depends on the order in which they are scheduled 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

35 Race Condition Race condition can still occur:
public void deposit(double amount) { balance = balance + amount; System.out.print("Depositing " + amount + ", new balance is " + balance); } Race condition can still occur: balance = the right-hand-side value

36 Conclusion Questions? Soon: Thread-safety Part 2 of Lab 8 is Online
Lab Now


Download ppt "CSE 501N Fall ‘09 21: Introduction to Multithreading"

Similar presentations


Ads by Google