320 likes | 435 Views
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:
E N D
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 SEA (WA)
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)
Start Finish Unix • Allows forking of new processes • ie multi-processing SEA (WA)
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)
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)
Option #1 • Subclass the Thread class • Defined in java.lang package • Override the run method SEA (WA)
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)
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)
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)
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)
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)
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)
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)
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)
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)
new • yield • End of quantum • interrupt runnable running waiting sleeping I/O blocked SEA (WA)
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)
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)
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)
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)
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)
Mutual exclusion • Eg bank balance • Credit thread • Debit thread SEA (WA)
Producer-Consumer put() producer 0 7 6 1 consumer 5 2 4 3 get() See pages 282- SEA (WA)
// 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)
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)
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)
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)
#2—locking a classic Method static synchronized void update() { • All objects in that class would be controlled SEA (WA)
#3—locking a block • Need to lock the block on an object static Object lock = new Object() … synchronized (lock) { … block of statements } SEA (WA)
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)
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)