JAVA Programming Language Chapter 7 Thread Computing Juho

  • Slides: 39
Download presentation
JAVA Programming Language Chapter 7. Thread Computing Juho Kim Department of Computer Science and

JAVA Programming Language Chapter 7. Thread Computing Juho Kim Department of Computer Science and Engineering Sogang University 7 -1

Exception/Thread Exception try ~ catch ~ Ibryuk Class Thread(Multi Thread) Thread Properties Thread Priorities

Exception/Thread Exception try ~ catch ~ Ibryuk Class Thread(Multi Thread) Thread Properties Thread Priorities Timers Calendar Class 7 -2

exception – What happens when a function is called with inappropriate inputs? • A

exception – What happens when a function is called with inappropriate inputs? • A function can fail safely. • A function can terminate : printing a message and terminating entire program. – Exception : Java allows functions to be terminated with messages that something has gone very wrong. (permissible error) • IO Exception : IOException EOFException File. Not. Found. Exception • Run. Time. Exception : Null. Pointer. Exception Array. Index. Out. Of. Bounds. Exception Arithmetic. Exception 7 -3

ex. Throws 1. java – void method() throws IOException : method() error IOException –

ex. Throws 1. java – void method() throws IOException : method() error IOException – int read() throws IOException : read 1 byte from input stream error IOException – System. out. flush() : Output and Clear the console buffer. import java. io. *; public class ex. Throws 1 { public static void main(String[] args) throws IOException { System. out. print("Mun. Ja. . . ? "); System. out. flush(); // flush the console buffer int ch = System. in. read(); } System. out. println((char)ch); } 7 -4

ex. Catch. java try ~ catch ~ (catching exceptions) try catch { one or

ex. Catch. java try ~ catch ~ (catching exceptions) try catch { one or more function calls that may cause an exception } { all possible exception types that try block is willing to handle } import java. io. *; class ex. Catch { public static void main(String[] args) { String str[] = {"JAVA", "Java", "java"}; int idx = Ibryuk. jung. Soo("idx. . . ? "); try { String s = str[idx]; System. out. println(s); int x = 100/idx; } catch(Runtime. Exception e) { System. out. println(e); } }} 7 -5

ex. Finally. java try ~ catch ~ finally try { function calls } catch

ex. Finally. java try ~ catch ~ finally try { function calls } catch { exceptions } finally { statements } If there is an error in function calls, exceptions are triggered and then statements are processed. If there is no error in function calls, statements are processed. import java. io. *; class ex. Finally { public static void main(String[] args) { String str[] = {"JAVA", "Java", "java"}; int idx = Ibryuk. jung. Soo("idx. . . ? "); try { System. out. println(str[idx]); } catch(Runtime. Exception e) { System. out. println(e); } finally { System. out. println("n. Sil. Haeng Jong. Ryo !"); } }} 7 -6

Ibryuk. java package java. lang; public class Ibryuk { public static String mun. Ja.

Ibryuk. java package java. lang; public class Ibryuk { public static String mun. Ja. Yul(String msg) { System. out. print(msg); // msg System. out. flush(); // flush system buffer String str = ""; boolean keut = false; int ch; while (! keut) { try { ch = System. in. read(); if (ch < 0 || (char)ch == 'n') keut = true; else str = str + (char) ch; } catch (java. io. IOException e) { keut = true; } } return str; } 7 -7 String mun. Ja. Yul(String msg) char mun. Ja(String msg) int jung. Soo(String msg) double sil. Soo(String msg) String read. String()

Ibryuk. java public static char mun. Ja(String msg) { System. out. print(msg); // msg를

Ibryuk. java public static char mun. Ja(String msg) { System. out. print(msg); // msg를 출력한후 System. out. flush(); // 시스템 버퍼를 플러시 char ch='a'; try { ch = (char)System. in. read(); // 엔터 키를 키보드 버퍼에서 제거 } catch(java. io. IOException e) { } return ch; } public static int jung. Soo(String msg) { System. out. print(msg); // msg를 출력한후 System. out. flush(); // 시스템 버퍼를 플러시 while(true) { try { return Integer. value. Of(read. String(). trim()). int. Value(); } catch(Number. Format. Exception e) { System. out. println("Jung. Soo. Rul Ib. Ryuk!"); } } } 7 -8

Ibryuk. java public static double sil. Soo(String msg) { System. out. print(msg); // msg를

Ibryuk. java public static double sil. Soo(String msg) { System. out. print(msg); // msg를 출력한후 System. out. flush(); // 시스템 버퍼를 플러시 while(true) { try { return Double. value. Of(read. String(). trim()). double. Value(); } catch(Number. Format. Exception e) { System. out. println("Sil. Soo. Rul Ib. Ryuk!"); } } } public static String read. String() { boolean keut = false; int ch; If you store this to String r = ""; /Java/Lang/Ibryuk. class while (!keut) { try { ch = System. in. read(); if (ch < 0 || (char)ch == 'n') The java. lang package gets imported keut = true; automatically. else r = r + (char) ch; } catch(java. io. IOException e) { keut = true; } } return r; }} 7 -9

multithreading – Multitasking : the ability to have more than one program working at

multithreading – Multitasking : the ability to have more than one program working at what seems like the same time. • Cooperative multitasking (Non-preemptive) : Operating system cooperates with programs. (Window 3. 1) • Preemptive multitasking : Operating system makes decision which program should be processed. Much more efficient but hard to implement (Window NT, Windows 95 32 -bit programs) – Multithreading : Running more than one computation at the same time. • Thread : each computational unit • Multithreading is one level lower than multitasking – Difference between multiple processes and multiple threads • Each process has a complete set of its own variables. • Threads share data in the program in which they live. 7 - 10

multithread – Why multithreading? thread 1 thread 2 thread 3 ……. . Process 1

multithread – Why multithreading? thread 1 thread 2 thread 3 ……. . Process 1 Process 2 • Less overhead to create and destroy individual threads • Useful in practice : for example, a browser should have the ability to deal with multiple hosts or to open an e-mail window while downloading more data. Java itself uses a thread to do garbage collection in the background thus saving you the trouble of managing memory. 7 - 11

Bouncd. java import java. awt. *; import java. awt. event. *; public class Bounce

Bouncd. java import java. awt. *; import java. awt. event. *; public class Bounce extends Frame implements Action. Listener { private Canvas canvas; public Bounce() { canvas = new Canvas(); add("Center", canvas); Panel p = new Panel(); Button s = new Button("Start"); Button c = new Button("Close"); p. add(s); p. add(c); s. add. Action. Listener(this); c. add. Action. Listener(this); add("South", p); } public void action. Performed(Action. Event evt) { if (evt. get. Action. Command() == "Start") { Ball b = new Ball(canvas); b. bounce(); } Single thread example else if (evt. get. Action. Command() == "Close") System. exit(0); } public static void main(String[] args) { Frame f = new Bounce("Bounce"); f. set. Size(400, 300); Window. Destroyer listener = new Window. Destroyer(); // 윈도우 삭제 버튼 f. add. Window. Listener(listener); f. set. Visible(true); } 7 - 12 }

Bounce. java private Canvas box; The ball will move for 1000 moves private static

Bounce. java private Canvas box; The ball will move for 1000 moves private static final int XSIZE = 20; private static final int YSIZE = 20; Pushing close button while the ball private int x = 0; is moving, has no effect at all. private int y = 0; private int dx = 2; private int dy = 2; When you download a large picture class Ball { public Ball(Canvas c) { box = c; } file and you don’t want to see the rest, public void draw() { Graphics g = box. get. Graphics(); you want to stop the process. g. fill. Oval(x, y, XSIZE, YSIZE); g. dispose(); } public void move() { Graphics g = box. get. Graphics(); g. set. XORMode(box. get. Background()); g. fill. Oval(x, y, XSIZE, YSIZE); x += dx; y += dy; Dimension d = box. get. Size(); if (x < 0) { x = 0; dx = -dx; } if (x + XSIZE >= d. width) { x = d. width - XSIZE; dx = -dx; } if (y < 0) { y = 0; dy = -dy; } if (y + YSIZE >= d. height) { y = d. height - YSIZE; dy = -dy; } g. fill. Oval(x, y, XSIZE, YSIZE); g. dispose(); } public void bounce() { draw(); for (int i = 1; i <= 1000; i++) { move(); try { Thread. sleep(5); } catch(Interrupted. Exception e) {}} } } 7 - 13

Bounce. Thread. java – Multithread example : 2 threads • one thread for bouncing

Bounce. Thread. java – Multithread example : 2 threads • one thread for bouncing ball • main thread for user interface Thread() constructs a new thread. The thread User interface must have a run() method. You must start() thread the thread to activate its run() function. Ball thread start void run() You must add the code that you want to have executed in the thread. move sleep void start() starts this thread. This will cause the run() method to be called. The new thread runs concurrently. static void sleep() puts the currently executing thread to sleep for the specified number of milliseconds. 7 - 14

Bounce. Thread. java import java. awt. *; import java. awt. event. *; public class

Bounce. Thread. java import java. awt. *; import java. awt. event. *; public class Bounce. Thread extends Frame implements Action. Listener { private Canvas canvas; public Bounce. Thread() { canvas = new Canvas(); add("Center", canvas); Panel p = new Panel(); Button s = new Button("Start"); Button c = new Button("Close"); p. add(s); p. add(c); s. add. Action. Listener(this); c. add. Action. Listener(this); add("South", p); } public void action. Performed(Action. Event evt) { if (evt. get. Action. Command() == "Start") { Ball b = new Ball(canvas); b. start(); } else if (evt. get. Action. Command() == "Close") System. exit(0); } public static void main(String[] args) { Frame f = new Bounce. Thread(); f. set. Size(400, 300); Window. Destroyer listener = new Window. Destroyer(); f. add. Window. Listener(listener); f. set. Visible(true); 7 - 15 }}

Bounce. Thread. java private Canvas box; private static final int XSIZE = 20; private

Bounce. Thread. java private Canvas box; private static final int XSIZE = 20; private static final int YSIZE = 20; private int x = 0; private int y = 0; private int dx = 2; private int dy = 2; class Ball extends Thread { public Ball(Canvas c) { box = c; } public void draw() { Graphics g = box. get. Graphics(); g. fill. Oval(x, y, XSIZE, YSIZE); g. dispose(); } public void move() { Graphics g = box. get. Graphics(); g. set. XORMode(box. get. Background()); g. fill. Oval(x, y, XSIZE, YSIZE); x += dx; y += dy; Dimension d = box. get. Size(); if (x < 0) { x = 0; dx = -dx; } if (x + XSIZE >= d. width) { x = d. width - XSIZE; dx = -dx; } if (y < 0) { y = 0; dy = -dy; } if (y + YSIZE >= d. height) { y = d. height - YSIZE; dy = -dy; } g. fill. Oval(x, y, XSIZE, YSIZE); g. dispose(); } public void run() { draw(); for (int i = 1; i <= 1000; i++) { move(); try { Thread. sleep(5); } catch(Interrupted. Exception e) {}} } 7 - 16

Thread properties Thread States : new, runnable, blocked, dead – New When a thread

Thread properties Thread States : new, runnable, blocked, dead – New When a thread is created as new Ball(), it is not yet running. This means that it is in the new state. Start() method does memory allocation for the tasks. Top priority runnable threads Lower priority runnable threads Blocked threads – Runnable Once you invoke the start() method, the thread is runnable. A runnable thread may not yet be running. It is up to the operating system to give it time to do so. When the code inside thread begins executing, the thread is running. 7 - 17

thread sleep done sleeping start new suspend blocked resume runnable dead stop notify wait

thread sleep done sleeping start new suspend blocked resume runnable dead stop notify wait I/O complete block on I/O – Blocked • Someone calls the sleep() method of the thread => expiration of specified time • Someone calls the suspend() method of the thread => resume() method call • The thread calls the wait() method => notify • The thread calls an operation that is blocking on input/output, that is, an operation that will not return to its caller until input and output operations are complete. => finished I/O resumes to runnable state 7 - 18

– Dead Threads • It dies a natural death because the run method exits

– Dead Threads • It dies a natural death because the run method exits • It is killed because someone invoked its stop method. – Finding Out the State of Thread • boolean is. Alive() returns true if the thread has started and has not been stopped. • static void yield() causes the currently executing thread to yield. If there are other runnable threads, they will be scheduled next. • void suspend() suspend this thread. • void resume() resume this thread. This method is only valid after suspend() has been invoked. • void stop() kills the thread. 7 - 19

th. Pgwin. Cha. java import java. awt. *; import java. awt. event. *; public

th. Pgwin. Cha. java import java. awt. *; import java. awt. event. *; public class th. Pgwin. Cha extends Frame implements Action. Listener { private Canvas cvas; public th. Pgwin. Cha() { cvas = new Canvas(); add("Center", cvas); // 프레임에 그림상자 cvas를 배치 cvas. set. Background(Color. white); // cvas 바탕색 -> 하양 Panel p = new Panel(); // 프레임에 패널 p를 배치 Button pen = new Button("펭귄"); Button car = new Button("차"); Button end = new Button("종료"); p. add(pen); p. add(car); p. add(end); pen. add. Action. Listener(this); car. add. Action. Listener(this); end. add. Action. Listener(this); add("South", p); } public void action. Performed(Action. Event evt) { if (evt. get. Action. Command(). equals("펭귄")) new th. Idong(cvas, "/jhkim/class/JAVA/program/grim/PGWIN. GIF", 0). start(); else if (evt. get. Action. Command(). equals("차")) new th. Idong(cvas, "/jhkim/class/JAVA/program/grim/CHA. GIF", 1). start(); else if (evt. get. Action. Command(). equals("종료")) System. exit(0); // 실행끝 } 7 - 20

th. Pgwin. Cha. java public static void main(String[] args) { Frame f = new

th. Pgwin. Cha. java public static void main(String[] args) { Frame f = new th. Pgwin. Cha(); f. set. Size(500, 300); Window. Destroyer listener = new Window. Destroyer(); f. add. Window. Listener(listener); f. set. Visible(true); }} class th. Idong extends Thread { private Canvas cvas; private int x = 0, y, l=3; // img in x coordinate private Image img; public th. Idong(Canvas cv, String imgfile, int n) { cvas = cv; y = 30 + 100*n; img = Toolkit. get. Default. Toolkit(). get. Image(imgfile); Graphics g = cvas. get. Graphics(); g. set. XORMode(cvas. get. Background()); } public void run() { while (true) // infinite while loop IDong(); } 7 - 21

th. Pgwin. Cha. java public void IDong() { Graphics g = cvas. get. Graphics();

th. Pgwin. Cha. java public void IDong() { Graphics g = cvas. get. Graphics(); // img를 그리고 g. draw. Image(img , x, y, cvas); // 0. 03 초 동안 쉰 후 try { Thread. sleep(3); } catch(Interrupted. Exception e) {} // img를 지운다 g. draw. Image(img , x, y, cvas); Dimension d = cvas. get. Size(); if (x >= d. width-50) // reaching right side of window { x = d. width-50; l = -l; } if (x<0) // reaching left side of window { x = 0; l = -l; } x += l; } } 7 - 22

priority Thread Priorities – Every thread in Java has a priority. By default, a

priority Thread Priorities – Every thread in Java has a priority. By default, a thread inherits the priority of its parent thread. You can increase or decrease the priority of any thread with the set. Priority() method. You can set the priority to any value between MIN_PRIORITY (defined as 1) and MAX_PRIORITY (10). NORM_PRIORITY is defined as 5. – The highest-priority runnable thread keeps running until it either: • yields by calling the yield() method • ceases to be runnable (dying or entering to be blocked state) • is replaced by a higher-priority thread that has become runnable Ball b = new Ball(canvas, Color. black); b. set. Priority(Thread. NORM_PRIORITY); b. start(); 7 - 23

th. Sun. Wi. java public void action. Performed(Action. Event evt) { if (evt. get.

th. Sun. Wi. java public void action. Performed(Action. Event evt) { if (evt. get. Action. Command(). equals(“Penguin")) { th. Idong pgwin = new th. Idong(cvas, "/jhkim/class/JAVA/program/grim/PGWIN. GIF", 0); pgwin. set. Priority(Thread. NORM_PRIORITY); // normal pgwin. start(); } else if (evt. get. Action. Command(). equals("차")) { th. Idong cha = new th. Idong(cvas, "/jhkim/class/JAVA/program/grim/CHA. GIF", 1); cha. set. Priority(Thread. NORM_PRIORITY+2); // normal+2 cha. start(); } else if (evt. get. Action. Command(). equals("종료")) System. exit(0); } 7 - 24

timers – Java does not have a built-in timer class, but it is easy

timers – Java does not have a built-in timer class, but it is easy enough to build one using threads. In the run() method, timer goes to sleep for the specified interval, then notifies the target. class Timer extends Thread {. . . public void run() { while (true) { try { sleep(interval); } catch (Interrupted. Exception e) {} // notify target } } private interval; } In C or C++ programming, the timer object would hold a pointer to a function, and it would call that function periodically. For safety reasons, Java does not have function pointers. 7 - 25

th. Timer 1. java import java. awt. *; public class th. Timer 1 extends

th. Timer 1. java import java. awt. *; public class th. Timer 1 extends Frame { public th. Timer 1(String str) { super(str); add(new timer. Canvas()); } public static void main(String[] args) { Frame f = new th. Timer 1("Timer"); f. set. Size(500, 300); Window. Destroyer listener = new Window. Destroyer(); f. add. Window. Listener(listener); f. set. Visible(true); } } class timer. Canvas extends Canvas { public timer. Canvas() { new Timer(this, 1000). start(); set. Size(400, 250); } } 7 - 26

th. Timer 1. java class Timer extends Thread { private timer. Canvas tcvas; private

th. Timer 1. java class Timer extends Thread { private timer. Canvas tcvas; private int msec; public Timer(timer. Canvas t, int ms) { tcvas = t; msec = ms; } public void run() { while (true) { try { sleep(msec); } catch(Interrupted. Exception e) {} Pal. Cho(); } } private boolean pal=false; public void Pal. Cho() { if (pal) tcvas. set. Background(Color. red); // pal==true면 바탕색->빨강, false면 초록 else tcvas. set. Background(Color. green); pal = ! pal; // pal의 값을 true <-> false로 반전 tcvas. repaint(); } } 7 - 27

Clock threads Class Calendar – Calendar is an abstract base class for converting between

Clock threads Class Calendar – Calendar is an abstract base class for converting between a Date object and a set of integer fields such as YEAR, MONTH, DAY, HOUR, and so on. (A Date object represents a specific instant in time with millisecond precision. 8 - 28

Calendar 7 - 29

Calendar 7 - 29

Calendar 8 - 30

Calendar 8 - 30

Calendar 8 - 31

Calendar 8 - 31

Calendar 7 - 32

Calendar 7 - 32

Calendar 7 - 33

Calendar 7 - 33

Calendar 7 - 34

Calendar 7 - 34

Calendar 7 - 35

Calendar 7 - 35

Timer. Test. java import java. awt. *; import java. util. *; public class Timer.

Timer. Test. java import java. awt. *; import java. util. *; public class Timer. Test extends Frame { public Timer. Test() { set. Layout(new Grid. Layout(2, 3)); add(new Clock. Canvas("Seoul", 16)); add(new Clock. Canvas("Chicago", 1)); add(new Clock. Canvas("London", 7)); add(new Clock. Canvas("Moscow", 10)); add(new Clock. Canvas("Paris", 8)); add(new Clock. Canvas("Beijing", 15)); } public static void main(String[] args) { Frame f = new Timer. Test(); f. set. Size(450, 300); f. set. Background(Color. gray); Window. Destroyer listener = new Window. Destroyer(); f. add. Window. Listener(listener); f. set. Visible(true); } } 7 - 36

Timer. Test. java interface Timed { public void tick(Timer t); } class Timer extends

Timer. Test. java interface Timed { public void tick(Timer t); } class Timer extends Thread { public Timer(Timed t, int i) { target = t; interval = i; set. Daemon(true); } public void run() { while (true) { try { sleep(interval); } catch(Interrupted. Exception e) {} target. tick(this); } } } private Timed target; private interval; Daemon Threads set Daemon(true); This makes the timer thread a daemon thread. A daemon is simply a thread that has no other role in life than to serve others. When only daemon threads remain, then the program exits. There is no point in keeping the program running if all remaining threads are daemons. In a graphical application, the timer class threads do not affect the end of the program. It stays alive until the user closes the application. When the non-timer threads have finished their run() methods, the application will automatically terminate. 7 - 37

Timer. Test. java class Clock. Canvas extends Canvas implements Timed { public Clock. Canvas(String

Timer. Test. java class Clock. Canvas extends Canvas implements Timed { public Clock. Canvas(String c, int off) { city = c; offset = off; new Timer(this, 1000). start(); set. Size(125, 125); } public int base. X = 10; public int base. Y = 10; public int clock. W = 100; public int clock. H = 100; public int center = base. X + clock. H/2; public void paint(Graphics g) { g. set. Color(Color. white); g. fill. Oval(base. X, base. Y, clock. W, clock. H); double hour. Angle = 2 * Math. PI * (seconds - 3 * 60) / (12 * 60); double minute. Angle = 2 * Math. PI * (seconds - 15 * 60) / (60 * 60); double second. Angle = 2 * Math. PI * (seconds - 15) / 60; g. set. Color(Color. black); g. draw. Line(center, center + (int)(30 * Math. cos(hour. Angle)), center + (int)(30 * Math. sin(hour. Angle))); g. draw. Line(center, center + (int)(40 * Math. cos(minute. Angle)), center + (int)(40 * Math. sin(minute. Angle))); g. set. Color(Color. blue); g. draw. Line(center, center + (int)(45 * Math. cos(second. Angle)), center + (int)(45 * Math. sin(second. Angle))); g. set. Color(Color. black); g. draw. String(city, base. X, base. Y+clock. H+10); } 7 - 38

Timer. Test. java public void tick(Timer t) { Calendar right. Now = Calendar. get.

Timer. Test. java public void tick(Timer t) { Calendar right. Now = Calendar. get. Instance(); seconds = (right. Now. get(Calendar. HOUR) - LOCAL + offset)* 60 + right. Now. get(Calendar. MINUTE) * 60 + right. Now. get(Calendar. SECOND); repaint(); } 270 (x 1, y 1) r A (x 0, y 0) 180 –A x 1 = x 0 + r · cos(A) y 1 = y 0 + r · sin(A) 90 7 - 39 0