lecture 4 ja v a 46 935 somesh jha 1 inner classes flash
play

Lecture 4 JA V A (46-935) Somesh Jha 1 Inner Classes Flash - PDF document

Lecture 4 JA V A (46-935) Somesh Jha 1 Inner Classes Flash bac k to the class. A bstr actT ermStructur e There w as a whic h SlowYieldV olObje ct computed: ( i = 0) Dierence b et w een and c


  1. Lecture 4 JA V A (46-935) Somesh Jha 1

  2. Inner Classes Flash bac k to the class. A bstr actT ermStructur e � There w as a whic h SlowYieldV olObje ct � computed: ( i = 0) Di�erence b et w een and c ompute d yield { the market yield (otherwise) Di�erence b et w een c ompute d { and the volatility . volatility market The ob ject used b y the Clumsy! NewtonR aphson � solv er b elongs in the class. T ermStructur e Nob o dy else uses it. � 2

  3. Inner Classes (Con td) Put a class inside the YieldV olObje ct � class. T ermStructur e Nob o dy else except class can use T ermStructur e � the ct . YieldV olObje These are called classes . memb er � There are other kind of inner classes. (Read � Chapter 5). 3

  4. Co de F ragmen t /** Abstract class for building a BDT type interest-rate model. @author Somesh Jha */ package interestRate; import mathUtil.*; public abstract class TermStructure { private static final boolean DEBUG=false; //time horizon int T; //Used by the Newton-Raphson solver YieldVolObject slowYieldVolObj; NewtonRaphson slowSolver; //parameters of the BDT model double r[]; double k[]; //bond yields and yield volatilities //at time 0 double yield[]; double volatilities[]; //nodes[i] points to link list of //nodes with time i LinkList nodes[]; 4

  5. class YieldVolObject extends AbstractFunctionObject { //Yield and volatality are computed for the //bond of that maturity public int maturity; public YieldVolObject() { //call the constructor for the super class super(2); }//end of constructor //If i==0 calculate the yield and otherwise //calculate the vol. Use values as value //of r[t] and k[t] public double evaluate(int i, double val[]) { r[maturity-1]=val[0]; k[maturity-1]=val[1]; if (i==0) { double tempYield =slowYield(0,0,maturity) ; return(tempYield-yield[mat urity-1 ]); } else { double tempVol = slowLogVol(0,0,maturity) ; return(tempVol-volatilitie s[matur ity-1]); } }//end of evaluate }//end of YieldVolObject 5

  6. P oin ts to notice Notice that the class is de�ned YieldV olObje ct � inside the class. T ermStructur e Notice that has complete access YieldV olObje ct � to data of the class. T ermStructur e Nob o dy can access from outside. YieldV olObje ct � 6

  7. JA V A pac k ages W e ha v e or will co v er some classes from the � follo wing pac k ages: (Classes concerned with applets) java.applet { (Classes concerned with GUIs) java.awt { (Classes concerned with I/O) java.io { (Classes concerned with v arious java.util { utilit i es) (Classes concerned with java.net { net w orking) Whole list of pac k ages giv en on page 86-89 in � the b o ok. 7

  8. JA V A I/O pac k age W e co v ered v arious kind of I/O streams. � Ho w to read and write to a �le. � A v ery wide v ariet y of I/O pro vided b y JA V A. � 8

  9. JA V A utlitie s pac k age is in the pac k age. StingTokenizer java.util � Allo ws us to break a line in to tok ens for parsing. � Consider the follo wing fragmen t of co de. � String line=''hhh:xxx:ccc''; StringTokenizer tokenizer = new StringTokenizer(line,'':'') ; String firstToken = tokenizer.nextToken(); String secondToken = tokenizer.nextToken(); 9

  10. Other in teresting classes HashTable � Date � Random � Vector � Stack � Read ab out them on page 527. � 10

  11. pac k age ja v a.lang This pac k age is loaded up b y default . � String , Math , System , are all in this Double � pac k age. and are also de�ned in this Object Exception � pac k age. Read ab out it on page 442. � 11

  12. What is a thread? A is a lik e a program. Thr e ad � Tw o threads run indep enden tly lik e separate � programs. Di�erence is that threads run within a program � and hence can share v ariables. 12

  13. Concurren t Programming Threads enable concurren t programming. � Tw o separate tasks can b e going on in parallel in � a single program. Let us sa y y ou en ter the w ebsite. Blo omb er g � 13

  14. Concurren t Programming (con td) The follo wing tasks can b e going on in parallel: � V arious indexes b eing displa y ed in a b o x. { Hot news tic k er. { Asking the user to en ter a sto c k sym b ol. { All these separate tasks could b e handled b y � separate threads. 14

  15. A small example package threadRelated; public class MyThread extends Thread { public MyThread(String name) { super(name); }//end of MyThread public void run() { for(int i=0; i < 10; i++) { System.out.println(i+" "+getName()); try { sleep((int)Math.random()*1 000); } catch (InterruptedException e) {}; } System.out.println("DONE! "+getName()); }//end of run }//end of MyThread 15

  16. Constructor A thread class extends the JA V A class Thread � de�ned in the pac k age java.lang . The constructor tak es the name of thread as an � argumen t. What do es do? super(name) � 16

  17. metho d run Whenev er a thread is started, metho d is run � called. The metho d in this case go es through the run � lo op times. 10 sleep((int)Math.ran dom() *1000 ) susp ends � the thread for a random time. What is Math.random() ? � gets the name of the thread. getName() � 17

  18. Main Program package threadRelated; public class testMyThread { static public void main(String argv[]) { MyThread thread1 = new MyThread("put"); MyThread thread2 = new MyThread("call"); thread1.start(); thread2.start(); } } 18

  19. Main Program (Con td). There are t w o threads: and thread2 . thread1 � First thread has name and the second one put � call . The metho d on the thread starts the start � thread. 19

  20. When do es a thread stop? A thread stops when either of the follo wing � ev en ts happ en: metho d exits. run { metho d is called on the thread. stop { 20

  21. Output of the program 0 put 0 call 1 call 1 put 2 put 2 call 3 put 3 call 4 put 5 put 4 call 5 call 6 put 6 call 7 put 7 call 8 put 8 call 9 put 9 call DONE! put DONE! call 21

  22. Sync hronization Supp ose that there are t w o threads 1 and 2 T T � that share t w o v ariables and . i j Supp ose eac h thread incremen ts and then i � incremen ts b y the v alue of i . j W e can ha v e t w o sample executions sho wn on � the next slide. 22

  23. Tw o executions Initial value i=1 j=1 First exceution i = i+1 (T1 executes) j = j+i (T2 executes) i = i+1 (T2 executes) j = j+i (T1 exceutes) Second execution i = i+1 (T1 executes) j = j+i (T1 executes) i = i+1 (T2 executes) j = j+i (T2 executes) 23

  24. Inconsistency! First Exc eution � 1 observ es = 6. T j Se c ond Exc eution � 1 observ es = 3. T j Need to con trol access to shared v ariables. � A nswer: Synchronization � 24

  25. T o y T rading System Eac h trader en ters the transaction he/she just � made. A thread reads the transaction record pr o duc er � and puts in a queue. threads read records from the queue Consumer � and log it. 25

  26. T o y T rading Example (Fig) Consumer 1 Consumer 2 log log Trader Queue Producer Figure 1: A T o y T rading System 26

  27. Pro ducer Thread package threadRelated; import java.io.*; public class ProducerThread extends Thread { Queue myQueue; BufferedReader bSystemIn; public ProducerThread(String name, Queue q) { super(name); myQueue = q; bSystemIn = new BufferedReader(new InputStreamReader(System .in)); } public void run() { try { String line; while ((line = bSystemIn.readLine()) != null) { TraderEntry tEntry = new TraderEntry(line); myQueue.add(tEntry); }//end of while } catch (IOException e) { System.err.println("Excepti on occured "+e.getMessage()); } }//end of run } 27

  28. Constructor Constructor tak es: � Name of the thread. { The queue to put things in. { 28

  29. metho d run Reads a line from the screen. � Mak es that line in to a trader-en try . � Adds that trader-en try to the queue. � 29

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend