Download Java Threads and Concurrency: Creating, Managing, Synchronization, and Race Conditions and more Slides Object Oriented Programming in PDF only on Docsity!
Threads and Concurrency
What is a Thread?
- A separate “execution” that runs within a single program and can
perform a computational task independently and concurrently with
other threads
- Many applications do their work in just a single thread: the one that
called main() at startup
- But there may still be extra threads...
- ... Garbage collection runs in a “background” thread
- GUIs have a separate thread that listens for events and “dispatches” upcalls
- Today: learn to create new threads of our own
Concurrency
- Concurrency refers to a single program in which several threads are
running simultaneously
- Special problems arise
- They see the same data and hence can interfere with each other, e.g. if one
thread is modifying a complex structure like a heap while another is trying to
read it
- In we focus on two main issues:
Thread class in Java
- Threads are instances of the class Thread
- Can create many, but they do consume space & time
- The Java Virtual Machine created the thread that executes your main
method.
- Threads have a priority
- Higher priority threads are executed preferentially
- A newly created Thread has initial priority equal to the thread that created it
(but can change)
Creating a new Thread (Method 2)
class PrimeRun implements Runnable {
long a, b;
PrimeRun(long a, long b) {
this.a = a; this.b = b;
public void run() {
//compute primes between a and b
PrimeRun p = new PrimeRun(143, 195);
new Thread(p).start();
Example
Thread[Thread-0,5,main] 0 Thread[main,5,main] 0 Thread[main,5,main] 1 Thread[main,5,main] 2 Thread[main,5,main] 3 Thread[main,5,main] 4 Thread[main,5,main] 5 Thread[main,5,main] 6 Thread[main,5,main] 7 Thread[main,5,main] 8 Thread[main,5,main] 9 Thread[Thread-0,5,main] 1 Thread[Thread-0,5,main] 2 Thread[Thread-0,5,main] 3 Thread[Thread-0,5,main] 4 Thread[Thread-0,5,main] 5 Thread[Thread-0,5,main] 6 Thread[Thread-0,5,main] 7 Thread[Thread-0,5,main] 8 Thread[Thread-0,5,main] 9 public class ThreadTest extends Thread { public static void main(String[] args) { new ThreadTest().start(); for (int i = 0; i < 10; i++) { System. out .format("%s %d\n", Thread. currentThread (), i); } } public void run() { for (int i = 0; i < 10; i++) { System. out .format("%s %d\n", Thread. currentThread (), i); } } }
Example
Thread[main,5,main] 0 Thread[main,5,main] 1 Thread[main,5,main] 2 Thread[main,5,main] 3 Thread[main,5,main] 4 Thread[main,5,main] 5 Thread[Thread-0,6,main] 0 Thread[Thread-0,6,main] 1 Thread[Thread-0,6,main] 2 Thread[Thread-0,6,main] 3 Thread[Thread-0,6,main] 4 Thread[Thread-0,6,main] 5 Thread[Thread-0,6,main] 6 Thread[Thread-0,6,main] 7 Thread[Thread-0,6,main] 8 Thread[Thread-0,6,main] 9 Thread[main,5,main] 6 Thread[main,5,main] 7 Thread[main,5,main] 8 Thread[main,5,main] 9 public class ThreadTest extends Thread { public static void main(String[] args) { new ThreadTest().start(); for (int i = 0; i < 10; i++) { System. out .format("%s %d\n", Thread. currentThread (), i); } } public void run() { currentThread ().setPriority(6); for (int i = 0; i < 10; i++) { System. out .format("%s %d\n", Thread. currentThread (), i); } } }
Example
waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... done public class ThreadTest extends Thread { static boolean ok = true; public static void main(String[] args) { new ThreadTest().start(); for (int i = 0; i < 10; i++) { System. out .println("waiting..."); yield (); } ok = false; } public void run() { while ( ok ) { System. out .println("running..."); yield (); } System. out .println("done"); } } If threads happen to be sharing a CPU, yield allows other waiting threads to run. But if there are multiple cores, yield isn’t needed
Threads can pause
- When active, a thread is “runnable”.
- It may not actually be “running”. For that, a CPU must schedule it. Higher
priority threads could run first.
- A thread can also pause
- It can call Thread.sleep(k) to sleep for k milliseconds
- If it tries to do “I/O” (e.g. read a file, wait for mouse input, even open a file)
this can cause it to pause
- Java has a form of locks associated with objects. When threads lock an
object, one succeeds at a time.
Background (daemon) Threads
- In many applications we have a notion of “foreground” and
“background” (daemon) threads
- Foreground threads are the ones doing visible work, like interacting with the
user or updating the display
- Background threads do things like maintaining data structures (rebalancing
trees, garbage collection, etc)
- On your computer, the same notion of background workers explains
why so many things are always running in the task manager.
Race Conditions
Thread t
Thread t
- ...
- LOAD X
- ADD 1
- STORE X Suppose X is initially 5 ... after finishing, X=6! We “lost” an update
Settings where race conditions matter
- Two or more threads try to access something, and one or more want
to change it
- A for-each loop is iterating over a collection, but some thread
modifies the collection concurrently
- You want your program to do one thing at a time, e.g. so that the
user can fill in a form without being interrupted to fill in some other
form
- … this list is very partial!
Example – A Lucky Scenario
private Stack stack = new Stack(); public void doSomething() { if (stack.isEmpty()) return; String s = stack.pop(); //do something with s... } Suppose threads A and B want to call doSomething(), and there is one element on the stack
- thread A tests stack.isEmpty() false
- thread A pops ⇒ stack is now empty
- thread B tests stack.isEmpty() ⇒ true
- thread B just returns – nothing to do
Example – An Unlucky Scenario
private Stack stack = new Stack(); public void doSomething() { if (stack.isEmpty()) return; String s = stack.pop(); //do something with s... } Suppose threads A and B want to call doSomething(), and there is one element on the stack
- thread A tests stack.isEmpty() ⇒ false
- thread B tests stack.isEmpty() ⇒ false
- thread A pops ⇒ stack is now empty
- thread B pops ⇒ Exception!