Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Threads Just Java: C10–pages 251C11–pages 275- What is a Thread? • A single thread of control/execution – the normal sequential execution Start Finish Threads SEA (WA) 2 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 Threads SEA (WA) 3 Unix • Allows forking of new processes – ie multi-processing Start Finish Threads SEA (WA) 4 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. Threads SEA (WA) 5 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) Threads SEA (WA) 6 Option #1 • Subclass the Thread class – Defined in java.lang package • Override the run method Threads SEA (WA) 7 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()); } } Threads SEA (WA) 8 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 Threads SEA (WA) 9 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() ) Threads SEA (WA) 10 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(); } } Threads SEA (WA) 11 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) Threads SEA (WA) 12 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(); } } Threads SEA (WA) 13 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) { } Threads SEA (WA) 14 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(); } }Threads SEA (WA) 15 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. Threads SEA (WA) 16 new • yield • End of quantum runnable • interrupt running waiting Threads sleeping SEA (WA) I/O blocked 17 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 Threads SEA (WA) 18 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 Threads SEA (WA) 19 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++); } } Threads SEA (WA) 20 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() Threads SEA (WA) 21 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 Threads SEA (WA) 22 Mutual exclusion • Eg bank balance – Credit thread – Debit thread Threads SEA (WA) 23 Producer-Consumer producer put() 7 0 6 1 5 2 4 3 See pages 282Threads SEA (WA) consumer get() 24 #1—Locking methods() public class CP { private int [] circBuffer; … public synchronized int get() { // locked by Consumer … } // unlocked by Consumer public synchronized void put(int value) { // locked by Producer … } // unlocked by Producer } Threads SEA (WA) 25 • 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 Threads SEA (WA) 26 What if the buffer is empty? Consumer must wait NB should be in a while (empty) { } try { // wait for Producer to put value wait(); } catch (InterruptedException e) { } … notify(); // notify Producer return value; Threads SEA (WA) 27 What if the buffer is full? Producer must wait NB should be in a while (full) { } try { // wait for Consumer to get value wait(); } catch (InterruptedException e) { } … notify(); // notify Consumer Threads SEA (WA) 28 #2—locking a classic Method static synchronized void update() { • All objects in that class would be controlled Threads SEA (WA) 29 #3—locking a block • Need to lock the block on an object static Object lock = new Object() … synchronized (lock) { … block of statements } Threads SEA (WA) 30 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. Threads SEA (WA) 31 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. Threads SEA (WA) 32