1 / 32

Threads

Threads. Just Java: C10–pages 251- C11–pages 275-. Start. Finish. What is a Thread?. A single thread of control/execution the normal sequential execution. Why would you want more?. Need to do several things at the same time Eg Java’s Garbage Collector Client/server Daemons Note:

clint
Download Presentation

Threads

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Threads Just Java: C10–pages 251- C11–pages 275-

  2. Start Finish What is a Thread? • A single thread of control/execution • the normal sequential execution SEA (WA)

  3. Why would you want more? • Need to do several things at the same time • Eg Java’s Garbage Collector • Client/server • Daemons • Note: • Java is one of the few languages with threads SEA (WA)

  4. Start Finish Unix • Allows forking of new processes • ie multi-processing SEA (WA)

  5. Multiple threads • Forking is quite expensive • Instead have lightweight processes AKA threads • Several threads in a single program, • “running” at the same time and, • performing parts of the task. SEA (WA)

  6. Notice • There is only one “program” or “process” • The threads share that context • Each thread has its own • Program counter • Stack • (and thread local storage—ThreadsLocal) SEA (WA)

  7. Option #1 • Subclass the Thread class • Defined in java.lang package • Override the run method SEA (WA)

  8. public class MyThread extends Thread { public MyThread(String str) { super(str); } public void run() { for (int i = 0; i < 5; i++) { System.out.println(getName() + " " + i ); try { sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) {} } System.out.println("End " + getName()); } } SEA (WA)

  9. public class TestThreads { public static void main (String[] args) { new MyThread("A").start(); new MyThread("B").start(); } } C:\lab4> javac MyThreads.java C:\lab4> java TestThreads SEA (WA)

  10. Option #2 • Define a class that • implements the Runnable interface • from java.lang package • Provide a definition of the run method • Eg an Applet—already using extends extends JApplet implements Runnable • Need to get a runnable object new Thread( new myRunnable() ) SEA (WA)

  11. class MyRunnable implements Runnable { public void run() { System.out.println("MyRunnable is running"); try { sleep(1000); } catch (InterruptedException ie) { } } public static void main(String [] args) { Thread t = new Thread( new MyRunnable() ); t.start(); } } SEA (WA)

  12. Whoops! • This won’t compile • Why? • It is not a subclass of Threads and so • Has no implementation of sleep(and also this means the exception is not thrown) SEA (WA)

  13. class MyRunnable implements Runnable { public void run() { System.out.println("MyRunnable is running"); try { sleep(1000); } catch (InterruptedException ie) { } } public static void main(String [] args) { Thread t = new Thread( new MyRunnable() ); t.start(); } } SEA (WA)

  14. Need to get thread Thread t = Thread.currentThread(); • This is a static (classic?) method in Threads • Then you can say: try { t.sleep(1000); } catch (InterruptedException ie) { } SEA (WA)

  15. class MyRunnable2 implements Runnable { public void run() { System.out.println("MyRunnable2 is running"); Thread t = Thread.currentThread(); try { t.sleep(1000); } catch (InterruptedException ie) { } } public static void main(String [] args) { Thread t = new Thread( new MyRunnable2() ); t.start(); } } SEA (WA)

  16. Thread life cycle • Create a thread new MyThread("One") • Starting a thread aThread.start() • Creates system resources to run the thread • Schedules the thread to be runnable • Calls the thread's run method. SEA (WA)

  17. new • yield • End of quantum • interrupt runnable running waiting sleeping I/O blocked SEA (WA)

  18. Becoming runnable • start() is called on the thread • and this then calls run() • Time set for sleep ends • Another object uses notify or notifyAll • I/O completes SEA (WA)

  19. Becoming Not runnable • Calls the sleep() method • Calls the wait() method • for a specific condition to be satisfied • Calls the yield() method • Blocks on I/O SEA (WA)

  20. How do threads die? • They just complete • Ends (falls through the }) • a return is executed • an Exception is thrown public void run() { int i = 0; while (i < 10) { System.out.println("i = " + i++); } } SEA (WA)

  21. Priority • Threads have a priority from: lowest MIN_PRIORITY —1 highest MAX_PRIORITY —10 t1.setPriority( t1.getPriority() +1); • Priority starts as the same as parent’s • Higher priority threads pre-empt lower ones • Equal priority—? • Depends on whether threads are time-sliced • Can also use yield() SEA (WA)

  22. Kinds of Threads Programming • No interaction • Threads work on part of the whole problem • Act on shared data—mutual exclusion • Communicating data • Producer-Consumer • Daemons SEA (WA)

  23. Mutual exclusion • Eg bank balance • Credit thread • Debit thread SEA (WA)

  24. Producer-Consumer put() producer 0 7 6 1 consumer 5 2 4 3 get() See pages 282- SEA (WA)

  25. // locked by Consumer // unlocked by Consumer // locked by Producer // unlocked by Producer #1—Locking methods() public class CP { private int [] circBuffer; … public synchronized int get() { … } public synchronized void put(int value) { … } } SEA (WA)

  26. Note that this locks the object on which the method is acting • That is: • Each object has an associated monitor • This is an old idea from Prof. Hoare at Oxford SEA (WA)

  27. What if the buffer is empty? Consumer must wait try {// wait for Producer to put valuewait(); } catch (InterruptedException e) { }… notify(); // notify Producerreturn value; NB should be in a while (empty) { } SEA (WA)

  28. What if the buffer is full? Producer must wait try { // wait for Consumer to get valuewait(); } catch (InterruptedException e) { } …notify(); // notify Consumer NB should be in a while (full) { } SEA (WA)

  29. #2—locking a classic Method static synchronized void update() { • All objects in that class would be controlled SEA (WA)

  30. #3—locking a block • Need to lock the block on an object static Object lock = new Object() … synchronized (lock) { … block of statements } SEA (WA)

  31. Joining Threads public final void join() throws InterruptedException public final void join(long milliseconds) throws InterruptedException public final void join(long milliseconds, int nanoseconds) throws InterruptedException • For example: t.join() • waits for the Thread t to finish before continuing. SEA (WA)

  32. When does the app end? Java Virtual Machine continues until: • System.exit(n) is called • and the security manager permits it. • All threads (not daemon threads) have died • returning from the call to the run method • throwing an exception that propagates beyond the run method. SEA (WA)

More Related