multithreading
play

Multithreading Horstmann ch.9 Multithreading Threads Thread - PDF document

Multithreading Horstmann ch.9 Multithreading Threads Thread states Thread interruption Race condition Lock Built-in lock java.util.concurrent library Animation example Single vs. Multiple Threads Finish


  1. Multithreading Horstmann ch.9

  2. Multithreading • Threads • Thread states • Thread interruption • Race condition • Lock • Built-in lock • java.util.concurrent library • Animation example

  3. Single vs. Multiple Threads • Finish each line of bullets before ThreadTester1 starting new line • Allow simultaneous drawing of several ThreadTester2 lines

  4. Single vs. Multiple Threads Using single thread: in method actionPerformed: ... for (int i=0; i<10; i++) { ”draw single bullet”; Thread.sleep(500); } ...

  5. Running Threads public class MyRunnable implements Runnable { public void run() { thread action Specify action } } ... Runnable r = new MyRunnable(); Thread t = new Thread(r); t.start(); Construct thread from Runnable object Start thread

  6. Single vs. Multiple Threads Using multiple threads: Using single thread: In method actionPerformed: in method actionPerformed: Runnable r = new Runnable() { public void run() { ... for (int i=0; i<10; i++) { ”draw single bullet”; Thread.sleep(500); } } ... } Thread t = new Thread(r); t.start();

  7. QUIZ Multiple threads public static void main(String[] args) { How many threads? 1. One Runnable r1 = new Producer(); 2. Two Runnable r2 = new Producer(); 3. Three Thread t1 = new Thread(r1); 4. None Thread t2 = new Thread(r2); 5. I don’t know t1.start(); t2.start(); }

  8. Starting Two Threads public static void main(String[] args) { Runnable r1 = new Producer(); Runnable r2 = new Producer(); Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); t1.start(); t2.start(); }

  9. Multithreading • Threads • Thread states • Thread interruption • Race condition • Lock • Built-in lock • java.util.concurrent library • Animation example

  10. Thread states • Each thread has – State (new, runnable, blocked, dead), and – priority Thread blocked when •Sleeping •Waiting for I/O •Waiting to acquire lock •Waiting for condition Scheduler activates the runnable thread of max priority if • a thread has completed its time slice • a thread has blocked itself • a thread with higher priority has become runnable

  11. Output depends Thread scheduling on scheduler: “goddag” public static void main(String[] args) { “goddag” Runnable r1 = new Producer(“goddag”); “farvel” Runnable r2 = new Producer(“farvel”); “farvel” Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); “farvel” t1.start(); “goddag” t2.start(); “farvel” } … public class Producer implements Runnable { public Producer(String a) { greeting = a; } public void run() { try { for (int i = 1; i <= 10; i++) { System.out.println(i + ": " + greeting); Thread.sleep(100); } } catch (InterruptedException e) {} } private String greeting; }

  12. QUIZ Thread scheduling Thread T1 based on run method Which thread(s) are runnable public void run { throughout there ”lives” from try { Thread.sleep(100000); } start to termination? catch (InterruptedException e) {} 1. T1 2. T2 } 3. None 4. Both 5. I don’t know Thread T2 based on run method public void run { factor(785678564567385635789) } Integer factor method from ”noter” ch. 1 (it is slow)

  13. Multithreading • Threads • Thread states • Thread interruption • Race condition • Lock • Built-in lock • java.util.concurrent library • Animation example

  14. Thread interaction • Recursive Fibonacci – May take long time – Window freezes ThreadTester3 • Compute in separate threads – Old slow thread may overwrite result from new fast thread? – Interrupt old threads!

  15. Terminating Threads • Thread terminates when run exits • Or ask thread to finish by calling interrupt • Thread may check for interrupt by calling Thread.currentThread().isInterrupted() • sleep , wait throw InterruptedException when thread is interrupted

  16. private Thread t = null; public void actionPerformed(ActionEvent e) { if (t!=null) t.interrupt(); Runnable r = new Runnable() { public void run() { try { long res = fib(Integer.parseInt(input.getText())); if (!Thread.currentThread().isInterrupted()) recResult.setText(res+""); } catch (InterruptedException e) {} } }; Code of anonymous class implementing ActionListener t = new Thread(r); t.start(); } private long fib(int n) throws InterruptedException { if (Thread.currentThread().isInterrupted()) throw new InterruptedException(); if (n <= 1) return 1; else return fib(n - 1) + fib(n - 2); }

  17. The catch statement is empty? 1. Compiler error 2. Legal code, but better style to omit try-catch 3. Legal code, try-catch is necessary, but empty catch is bad style 4. Legal code, try-catch is necessary, empty catch is good style 5. I don’t know public class Test1 implements Runnable { QUIZ public void run() { try { for (int i=1; i<=10; i++) { Thread termination System.out.println(i); Thread.sleep(1000); } } catch (InterruptedException e) { } } }

  18. Multithreading • Threads • Thread states • Thread interruption • Race condition • Lock • Built-in lock • java.util.concurrent library • Animation example

  19. Shared Resource Producer Thread ”goddag” Consumer Queue Thread object Producer Thread ”farvel” Bounded Queue: max 10 elements

  20. Producer Thread int i = 1; while (i <= 100) { if (! queue .isFull()) { queue .add(i + ": " + greeting); i++; } Thread.sleep((int)(Math.random() * DELAY)); } Producer Thread ”goddag” Consumer Queue Thread object Producer Thread ”farvel” Bounded Queue: max 10 elements

  21. Consumer Thread int i = 1; while (i <= 200) { if (! queue .isEmpty()) { Object greeting = queue .remove(); System.out.println(greeting); i++; } Thread.sleep((int)(Math.random() * DELAY)); } Producer Thread ”goddag” Consumer Queue Thread object Producer Thread ”farvel” Bounded Queue: max 10 elements

  22. • Expected Program • Possible output Output ... 10: goddag 1: goddag 11: farvel 1: farvel ... 2: goddag 15: goddag 3: goddag 11: farvel ... ... 99: farvel 100: farvel • Why?

  23. Queue: Circular Array Implementation <junk> 3 <junk> 2 Tail: <junk> Head: 1 4 <junk> 3 <junk> 2 <junk> Tail: Head: 1 <junk> <junk> 4 public void add(E newValue) { elements[tail] = newValue; tail++; size++; if (tail == elements.length) { tail = 0; } }

  24. Race Condition • First thread calls add and executes elements[tail] = newValue; First thread at end of time slice • Second thread calls add and executes elements[tail] = newValue; tail++; Second thread at end of time slice • First thread executes tail++;

  25. Could race condition occur when QUIZ Race condition running these thread in parallel? 1. Yes 2. No Producer Thread: 3. I don’t know BoundedQueue<String> queue = new BoundedQueue<String>(10); for (int i = 1; i <= 100; i++) { queue .add(i + ": " + greeting); Thread.sleep((int)(Math.random() * DELAY)); } Consumer Thread: BoundedQueue<String> queue = new BoundedQueue<String>(10); for (int i = 1; i <= 100; i++) { Object greeting = queue .remove(); System.out.println(greeting); Thread.sleep((int)(Math.random() * DELAY)); }

  26. Multithreading • Threads • Thread states • Thread interruption • Race condition • Lock • Built-in lock • java.util.concurrent library • Animation example

  27. Locks • Thread can acquire lock • When another thread tries to acquire same lock, it blocks • When first thread releases lock, other thread is unblocked and tries again • Two kinds of locks – Objects of class implementing java.util.concurrent.Lock interface type, usually ReentrantLock – Locks that are built into every Java object

  28. Consumer or producer thread executing lock() has exclusive access to add/remove methods – even when time slice is up – until unlock() private Lock aLock = new ReentrantLock(); . . . public void add(E newValue) { public E remove() { aLock. lock (); aLock. lock (); try { try { elements[tail] = newValue; E r = (E) elements[head]; tail++; head++; size++; size--; if (tail==elements.length) if (head==elements.length) tail = 0; head = 0; } finally { return r; aLock. unlock (); } finally { } aLock. unlock (); } } }

  29. Producer Thread int i = 1; Bad: Another producer thread while (i <= 100) { may fill up the queue between isFull() check and add() if (! queue .isFull()) { Good: add is queue .add(i + ": " + greeting); protected by lock i++; } Thread.sleep((int)(Math.random() * DELAY)); } Solution: Must move isFull() check inside protected add()

  30. QUIZ Dead lock Does it work to put isfull() check inside lock protected add() ? 1. No, race condition may still occur 2. Yes, race condition cannot occur, and this code works fine 3. No, race condition cannot occur – but a new problem arises… 4. I don’t know public void add(E newValue) throws InterruptedException { aLock. lock (); try { while( isFull() ) { Thread.sleep(1000); } ... } finally {aLock. unlock ();} }

Recommend


More recommend