330 likes | 431 Views
스레드 프로그래밍. Lecture #7. 강의 목차. 스레드 개념을 이해한다 . Thread 클래스에서 제공하는 메소드의 종류와 기능을 알아본다 . 스레드를 생성하고 실행하는 방법을 알아본다 . 멀티 스레드 개념을 이해하고 , 동기화 방법을 익힌다. 스레드 개요 (1). 스레드 (Thread) 란 ? 한 프로그램 내에서 독립적으로 동작하는 일의 실행 단위 한 프로그램 내에 여러 개의 스레드를 생성 , 실행 가능 생각해 봅시다 ! paint() 메서드를 반복시키기 위한 방법 ?
E N D
스레드 프로그래밍 Lecture #7
강의 목차 • 스레드 개념을 이해한다. • Thread 클래스에서제공하는 메소드의 종류와 기능을 알아본다. • 스레드를 생성하고 실행하는 방법을 알아본다. • 멀티 스레드 개념을 이해하고, 동기화 방법을 익힌다 . Mobile Programming
스레드 개요 (1) • 스레드(Thread)란? • 한 프로그램 내에서 독립적으로 동작하는 일의 실행 단위 • 한 프로그램 내에 여러 개의 스레드를 생성, 실행 가능 • 생각해 봅시다! • paint() 메서드를반복시키기 위한 방법? • 명령어 버튼을 클릭 : 불연속 • while , for, do while 문 이용 : X • 스레드이용 Mobile Programming
스레드 개요 (2) • 스레드 이용 방법 [예제 6-1] ClipAniThreadMIDlet.java 01 import javax.microedition.midlet.*; 02 import javax.microedition.lcdui.*; 03 04 public class ClipAniThreadMIDlet extends MIDlet { 05 private Display display; 06 private ClipAniThreadCanvas canvas_; 07 public ClipAniThreadMIDlet() { 08 display = Display.getDisplay(this); 09 canvas_ = new ClipAniThreadCanvas(); 10 } 11 public void startApp() { 12 display.setCurrent(canvas_); 13 } 14 public void pauseApp() { } 15 public void destroyApp(boolean unconditional) { } 16 } Mobile Programming
스레드 개요 (3) • 스레드 이용 방법 … 04 class ClipAniThreadCanvas extends Canvas implements Runnable { …. 07 private Thread thread; 08 public ClipAniThreadCanvas() { …. 14 thread = new Thread(this); 15 thread.start(); 16 } 17 public void run() { 18 while(true) { 19 try { 20 Thread.sleep(500); 21 } catch(InterruptedException e) { 22 System.out.println(e); 23 } 24 repaint(); 25 } 26 } [예제 6-2] ClipAniThreadCanvas.java Mobile Programming
스레드 개요 (4) • 스레드 구현 방법 • Runnable 인터페이스를 이용한 방법 • Thread 클래스를 이용한 방법 • Runnable 인터페이스를 이용한 방법 • Runnable 인터페이스 상속 • 스레드 선언 • 스레드 객체 생성 • 스레드 실행 • run() 메소드 구현 Mobile Programming
스레드 개요 (5) • Runnable 인터페이스를 이용한 방법 ➊ class ClipAniThreadCanvas extends Canvas implements Runnable { private Thread thread; public RunnableThreadCanvas( ) { thread = new Thread(this); thread.start( ); } public void run( ) { ... repaint( ); // paint( ) 호출 } public void paint(Graphics g) { ... } } ➋ ➌ ➍ ➎ Mobile Programming
스레드 개요 (6) • Thread 클래스를 이용한 방법 • Runnable 인터페이스를 이용하는 방법과 다르다. • Thread 클래스를상속받는 클래스가 필요 • Thread 클래스를이용하여 게임 프로그램을 만들기 위해서는 최소 다음과 같은 3개의 클래스가 필요 • MIDlet 클래스를 상속받는 ThreadMIDlet 클래스 • Canvas 클래스를 상속받는 ThreadCanvas 클래스 • Thread 클래스를 상속받는 ThreadClass 클래스 Mobile Programming
스레드 개요 (7) ➊ • MIDlet 클래스를 상속받는 ThreadMIDlet 클래스 public class ThreadMIDlet extends MIDlet { private Display display; private ThreadCanvas canvas; public ThreadMIDlet( ) { display = Display.getDisplay(this); canvas = new ThreadCanvas(); } public void startApp( ){ display.setCurrent(canvas); } public void pauseApp( ) { ... } public void destroyApp(boolean unconditional) { ... } } ➋ ➌ Mobile Programming
스레드 개요 (8) • Canvas 클래스를 상속받는 ThreadCanvas 클래스 ➊ class ThreadCanvas extends Canvas { ThreadClass thread_class; public ThreadCanvas( ) { thread_class = new ThreadClass(this); } public void paint(Graphics g) { ... } } ➋ ➌ Mobile Programming
스레드 개요 (9) • Thread 클래스를 상속받는 ThreadClass 클래스 ➊ class ThreadClass extends Thread { private Thread thread; ThreadCanvas thread_canvas; public ThreadClass(ThreadCanvas thread_canvas) { this.thread_canvas = thread_canvas; thread = new Thread(this); thread.start( ); } public void run( ) { ... thread_canvas.repaint(); } } ➋ ➌ ➍ ➎ ➏ ➐ ➑ ➒ Mobile Programming
스레드 개요 (10) 01 import javax.microedition.midlet.*; 02 import javax.microedition.lcdui.*; 03 04 public class ThreadMIDlet extends MIDlet { 05 private Display display; 06 private ThreadCanvas canvas; 07 public ThreadMIDlet() { 08 display = Display.getDisplay(this); 09 canvas = new ThreadCanvas(); 10 } 11 public void startApp() { 12 display.setCurrent(canvas); 13 } 14 public void pauseApp() { } 15 public void destroyApp(boolean unconditional) { } 16 } [예제 6-3] ThreadMIDlet.java Mobile Programming
스레드 개요 (11) 01 import javax.microedition.lcdui.*; 02 import java.io.*; 03 class ThreadCanvas extends Canvas { 04 private Image ani_img; 05 private int curFrame; 06 ThreadClass thread_class; 07 08 public ThreadCanvas() { 09 try { 10 ani_img = Image.createImage("/animation.png"); 11 } catch(IOException e) { 12 e.printStackTrace(); 13 } 14 curFrame = 0; 15 thread_class = new ThreadClass(this); 16 } 17 public void paint(Graphics g) { 18 g.setColor(0, 0, 0); 19 g.drawRect(0, 0, getWidth(), getHeight()); 20 int x = getWidth() / 2-33; 21 int y = getHeight() / 2-27; 22 g.setClip(x, y, 66, 54); 23 g.drawImage(ani_img, x-(66*curFrame), y, Graphics.TOP | Graphics.LEFT); 24 g.setClip(0, 0, getWidth(), getHeight()); 25 this.curFrame++; 26 if(curFrame >= 10) curFrame = 0; 27 } 28 } [예제 6-4] ThreadCanvas.java Mobile Programming
스레드 개요 (12) 01 public class ThreadClass extends Thread { 02 private Thread thread; 03 ThreadCanvas thread_canvas; 04 public ThreadClass(ThreadCanvas thread_canvas) { 05 this.thread_canvas = thread_canvas; 06 thread = new Thread(); 07 thread.start(); 08 } 09 public void run() { 10 while(true) { 11 try { 12 thread.sleep(500); 13 } catch(InterruptedException e) { 14 System.out.println(e); 15 } 16 thread_canvas.repaint(); 17 } 18 } 19 } [예제 6-5] ThreadClass.java Mobile Programming
Thread Class (1) • Thread 클래스의 생성자 Mobile Programming
Thread Class (2) • Thread 클래스의 메소드 Mobile Programming
Thread Class (3) • 스레드 상태 전이도 • Java.lang.Object 클래스에서 상속받은 메소드 생성 run( ) 실행 일시정지 start( ) new yield( ) 스케줄러 wait( ) notify( ) nofifyAll( ) sleep( ) 인터럽트 정지 Mobile Programming
Thread Class (4) • 스레드 생성 class ThreadCanvas extends Canvas { ThreadClass thread_class; public ThreadCanvas( ) { thread_class = new ThreadClass(this); Thread thread = new Thread(thread_class); thread.start(); } public void paint(Graphics g) { ... } } • Thread t1 = new Thread(this); • Thread t2 = new Thread(this, “thread_name”); Mobile Programming
Thread Class (5) • 스레드 상태 검사 • 현재 스레드가 살아있는지 확인 • 살아있는 상태: true 반환 • 종료: false 반환 • public final boolean isAlive( ) Mobile Programming
Thread Class (6) • 스레드 우선 순위 • 우선 순위 설정 및 확인 • setPriority( ) 메소드 • getPriority( ) 메소드 Thread.currentThread( ).setPriority(Thread.NORM_PRIORITY+2); t1.setPriority(7); Thread.currentThread().getPriority( ); • Thread.MIN_PRIORITY : 최소 우선순위 값(=1) • Thread.NORM_PRIORITY : 기본 우선순위 값(=5) • Thread.MAX_PRIORITY : 최대 우선순위 값(=10) Mobile Programming
Thread Class (7) • 스레드 기본 상태 전이 • 스레드 실행을 일시적으로 정지했다가 다시 실행시키는 메소드 • sleep( ), join( ), yield( ) • sleep( ) • 사용 예 • static void sleep(long millis) • throws InterruptedException try { Thread.sleep((int)(1000)); } catch (InterruptedException e) { System.out.println(e); } Mobile Programming
Thread Class (8) • join( ) • 호출한 스레드를 종료할 때까지 현재 스레드를 기다림 • yield( ) • 우선순위가 같은 실행 가능 상태에 있는 다른 스레드를 수행하도록 CPU를 양보 • public final void join( ) • throws InterruptedException • public static void yield( ) Mobile Programming
Thread Class (9) • 멀티 스레드 • 하나의 자원을 공유하면서 여러 작업을 동시 수행 • 두 스레드 간에 발생할 수 있는 문제점 • 자원 공유에 따른 상호배제(Mutual Exclusion) • 해결 방법으로 스레드 동기화 기능을 제공 Mobile Programming
Thread Class (10) • 동기화로 두 스레드 간의 문제점 해결 • synchronized 키워드를 사용해 임계 영역 설정 • 예제 6-6 참조 Mobile Programming
스레드 실전 프로그래밍 (1) • 별 애니메이션 프로그램 • 초기화면: 별 하나 등장 • 임의의 방향으로 이동 • 상하 좌우 벽면에 부딪치면 튕겨져 다른 방향으로 이동 • 우측 버튼을 클릭하면 : 별이 하나씩 증가 • 좌측 버튼을 클릭하면 : 별이 하나씩 감소 • 상하 버튼을 클릭하면: 별의 속도 증, 감 Mobile Programming
스레드 실전 프로그래밍 (2) • 프로그램 구성도 • ThreadStarMIDlet 클래스 • ThreadStarCanvas 클래스 • ThreadStarClass 클래스 • 예제 6-7 ~6-9 참조 Midlet Canvas Thread ThreadS ThreadStarMIDlet() starApp( ) pauseApp( ) destroyApp( ) ThreadStarMIDlet ThreadStarCanvas( ) Paint( ) keyPressed( ) ThreadStarCanvas ThreadStarClass( ) setStarPaint( ) slower( ) faster( ) ThreadStarClass 1 1 1 n Mobile Programming
스레드 실전 프로그래밍 (3) 01 import javax.microedition.midlet.*; 02 import javax.microedition.lcdui.*; 03 04 public class ThreadStarMIDlet extends MIDlet { 05 private Display display; 06 private ThreadStarCanvas canvas; 07 public ThreadStarMIDlet( ) { 08 display = Display.getDisplay(this); 09 canvas = new ThreadStarCanvas(); 10 } 11 public void startApp( ) { 12 display.setCurrent(canvas); 13 } 14 public void pauseApp( ) { } 15 public void destroyApp(boolean unconditional) { } 16 } [예제 6-7] ThreadStarMIDlet.java Mobile Programming
스레드 실전 프로그래밍 (4) • … • 03 class ThreadStarCanvas extends Canvas { • 04 private Image star_bg_img; • 05 private int stars_num, width, height; • 06 private int maxStars = 5; • 07 private ThreadStarClass[] stars; • 08 private ThreadStarClass thread_star_class; • 09 • 10 public ThreadStarCanvas() { • 11 width = getWidth(); • 12 height = getHeight(); • 13 try { • 14 star_bg_img = Image.createImage("/star_bg.png"); • 15 } catch(IOException e) { • 16 e.printStackTrace(); • 17 } • 18 stars = new ThreadStarClass[maxStars]; • 19 stars[0] = new ThreadStarClass(this, 0, 0, width, height); • 20 stars_num = 1; • 21 Thread t = new Thread(stars[0]); • 22 t.start(); • } [예제 6-8] ThreadStarCanvas.java Mobile Programming
스레드 실전 프로그래밍 (5) • 24 public void paint(Graphics g) { • 25 g.setColor(0, 0, 0); • 26 g.drawRect(0, 0, getWidth(), getHeight()); • 27 g.drawImage(star_bg_img, 0, 0, Graphics.TOP | Graphics.LEFT); • 28 for(int i=0; i < stars_num; i++) { • 29 stars[i].setStarPaint(g); • } • 31 g.setColor(0xffffff); • 32 g.drawString(stars_num + "stars", 5, height-14, 0); • 33 } • 34 public void keyPressed(int keyCode) { • 35 int action = getGameAction(keyCode); • 36 switch(action) { • 37 case LEFT: • 38 if(stars_num > 0) { • 39 stars_num = stars_num - 1; • 40 } • 41 break; [예제 6-8] ThreadStarCanvas.java Mobile Programming
스레드 실전 프로그래밍 (6) 42 case RIGHT: 43 if(stars_num < stars.length) { 44 stars[stars_num] = new ThreadStarClass(this, 0, 0, width, height-12); 45 new Thread(stars[stars_num]).start(); 46 stars_num = stars_num + 1; 47 } 48 break; 49 case UP: 50 thread_star_class.faster(); 51 break; 52 case DOWN: 53 thread_star_class.slower(); 54 break; 55 } 56 repaint(); 57 } 58 } [예제 6-8] ThreadStarCanvas.java Mobile Programming
스레드 실전 프로그래밍 (7) • ... • 03 public class ThreadStarClass extends Thread { • 04 static java.util.Random random = new java.util.Random(); • 05 static int[][] matrix = {{1,-1, -1, 1, 1, 1}, {-1,-1, 1, 1, -1, 1}, null, {1, 1, -1, -1, 1, -1}, {-1, 1, 1, -1, -1, -1}}; • 06 static int delay = 20; • 07 Image star_image; • 08 public int top, left, width, height; • 09 public int posX, posY; • 10 public int star_radius = 10; • 11 public int deltaX, deltaY; • 12 Canvas canvas; • 13 public ThreadStarClass(Canvas c, int left, int top, int width, int height) { • 14 canvas = c; • 15 this.left = left; • 16 this.top = top; • 17 this.width = width - (2 * star_radius + 2); • 18 this.height = height - (2 * star_radius + 2); • 19 this.posX = (random.nextInt()>>>1) % (this.width-20) + 10; • 20 this.posY = (random.nextInt()>>>1) % (this.height-20) + 10; • 21 deltaX = random.nextInt() & 1; • deltaY = random.nextInt() & 1; [예제 6-9] ThreadStarclass.java Mobile Programming
스레드 실전 프로그래밍 (8) • 23 try { • 24 star_image = Image.createImage("/star.png"); • 25 } catch(Exception e) { • 26 System.out.println("Image Loading Fail"); • 27 } • } • 29 public void run() { • 30 System.out.println("getName= " + Thread.currentThread().getName()); • 31 int right = left + width; • int bottom = top + height; • 33 while(true) { • 34 int direction = deltaX + deltaY; • 35 if(direction == 0) direction = deltaX + 2*deltaY; • 36 int collision = 0; • 37 if(posX <= left || posX >= right) collision++; • 38 if(posY <= top || posY >= bottom) collision += 2; • 39 if(collision != 0) { • 40 collision = (collision - 1) * 2; • 41 deltaX = matrix[direction+2][collision]; • 42 deltaY = matrix[direction+2][collision+1]; • 43 } [예제 6-9] ThreadStarclass.java Mobile Programming
스레드 실전 프로그래밍 (9) 44 posX = posX + deltaX; 45 posY = posY + deltaY; 46 canvas.repaint(); 47 try { 48 Thread.sleep(delay); 49 } catch(InterruptedException e) { } 50 } 51 } 52 void setStarPaint(Graphics g) { 53 g.drawImage(star_image,posX,posY,Graphics.TOP|Graphics.LEFT); 54 } 55 static void slower() { 56 delay += 10; 57 if(delay > 100) delay = 100; 58 } 59 static void faster() { 60 delay -= 10; 61 if(delay < 0) delay = 0; 62 } 63 } [예제 6-9] ThreadStarclass.java Mobile Programming