Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Threads Just Java: C10–pages 251- C11–pages 275-"— Presentation transcript:

1

2 Threads Just Java: C10–pages 251- C11–pages 275-

3 ThreadsSEA (WA)2 What is a Thread? A single thread of control/execution –the normal sequential execution Start Finish

4 ThreadsSEA (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

5 ThreadsSEA (WA)4 Unix Allows forking of new processes –ie multi-processing Start Finish

6 ThreadsSEA (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.

7 ThreadsSEA (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)

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

9 ThreadsSEA (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()); }

10 ThreadsSEA (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

11 ThreadsSEA (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() )

12 ThreadsSEA (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(); }

13 ThreadsSEA (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)

14 ThreadsSEA (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(); }

15 ThreadsSEA (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) { }

16 ThreadsSEA (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(); }

17 ThreadsSEA (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.

18 ThreadsSEA (WA)17 new running sleepingwaitingI/O blocked runnable yield End of quantum interrupt

19 ThreadsSEA (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

20 ThreadsSEA (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

21 ThreadsSEA (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++); } }

22 ThreadsSEA (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()

23 ThreadsSEA (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

24 ThreadsSEA (WA)23 Mutual exclusion Eg bank balance –Credit thread –Debit thread

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

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

27 ThreadsSEA (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

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

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

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

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

32 ThreadsSEA (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.

33 ThreadsSEA (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.


Download ppt "Threads Just Java: C10–pages 251- C11–pages 275-"

Similar presentations


Ads by Google