스레드 프로그래밍

33
스스스 스스스스스 스스스 스스스스스 Lecture #7 Lecture #7

description

스레드 프로그래밍. Lecture #7. 강의 목차. 스레드 개념을 이해한다 . Thread 클래스에서 제공하는 메소드의 종류와 기능을 알아본다 . 스레드를 생성하고 실행하는 방법을 알아본다 . 멀티 스레드 개념을 이해하고 , 동기화 방법을 익힌다. 스레드 개요 (1). 스레드 (Thread) 란 ? 한 프로그램 내에서 독립적으로 동작하는 일의 실행 단위 한 프로그램 내에 여러 개의 스레드를 생성 , 실행 가능 생각해 봅시다 ! paint() 메서드를 반복시키기 위한 방법 ? - PowerPoint PPT Presentation

Transcript of 스레드 프로그래밍

Page 1: 스레드 프로그래밍

스레드 프로그래밍스레드 프로그래밍

Lecture #7Lecture #7

Page 2: 스레드 프로그래밍

강의 목차강의 목차

▶ 스레드 개념을 이해한다 .▶ Thread 클래스에서 제공하는 메소드의 종류와 기능을

알아본다 . ▶ 스레드를 생성하고 실행하는 방법을 알아본다 .▶ 멀티 스레드 개념을 이해하고 , 동기화 방법을 익힌다 .

2Mobile Programming

Page 3: 스레드 프로그래밍

스레드 개요스레드 개요 (1)(1)

▶ 스레드 (Thread) 란 ?▷ 한 프로그램 내에서 독립적으로 동작하는 일의 실행 단위▷ 한 프로그램 내에 여러 개의 스레드를 생성 , 실행 가능

▶ 생각해 봅시다 !▷ paint() 메서드를 반복시키기 위한 방법 ?

명령어 버튼을 클릭 : 불연속 while , for, do while 문 이용 : X 스레드 이용

3Mobile Programming

Page 4: 스레드 프로그래밍

스레드 개요스레드 개요 (2)(2)

▶ 스레드 이용 방법

4Mobile Programming

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 }

[ 예제 6-1] ClipAniThreadMIDlet.java

[ 예제 6-1] ClipAniThreadMIDlet.java

Page 5: 스레드 프로그래밍

스레드 개요스레드 개요 (3)(3)

▶ 스레드 이용 방법

5Mobile Programming

…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[ 예제 6-2] ClipAniThreadCanvas.java

Page 6: 스레드 프로그래밍

스레드 개요스레드 개요 (4)(4)

▶ 스레드 구현 방법▷ Runnable 인터페이스를 이용한 방법

▷ Thread 클래스를 이용한 방법

▶ Runnable 인터페이스를 이용한 방법➊ Runnable 인터페이스 상속

➋ 스레드 선언

➌ 스레드 객체 생성

➍ 스레드 실행

➎ run() 메소드 구현

6Mobile Programming

Page 7: 스레드 프로그래밍

스레드 개요스레드 개요 (5)(5)

▶ Runnable 인터페이스를 이용한 방법

7Mobile Programming

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) { ... }}

Page 8: 스레드 프로그래밍

스레드 개요스레드 개요 (6)(6)

▶ Thread 클래스를 이용한 방법▷ Runnable 인터페이스를 이용하는 방법과 다르다 .

▷ Thread 클래스를 상속받는 클래스가 필요

▶ Thread 클래스를 이용하여 게임 프로그램을 만들기 위해서는 최소 다음과 같은 3 개의 클래스가 필요

① MIDlet 클래스를 상속받는 ThreadMIDlet 클래스

② Canvas 클래스를 상속받는 ThreadCanvas 클래스

③ Thread 클래스를 상속받는 ThreadClass 클래스

8Mobile Programming

Page 9: 스레드 프로그래밍

스레드 개요스레드 개요 (7)(7)

▶ MIDlet 클래스를 상속받는 ThreadMIDlet 클래스

9Mobile Programming

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) { ... }

}

Page 10: 스레드 프로그래밍

스레드 개요스레드 개요 (8)(8)

▶ Canvas 클래스를 상속받는 ThreadCanvas 클래스

10Mobile Programming

class ThreadCanvas extends Canvas {

ThreadClass thread_class;

public ThreadCanvas( ) {

thread_class = new ThreadClass(this);

}

public void paint(Graphics g) { ... }

}

Page 11: 스레드 프로그래밍

스레드 개요스레드 개요 (9)(9)

▶ Thread 클래스를 상속받는 ThreadClass 클래스

11Mobile Programming

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

}}

➏➐

Page 12: 스레드 프로그래밍

스레드 개요스레드 개요 (10)(10)

12Mobile Programming

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[ 예제 6-3] ThreadMIDlet.java

Page 13: 스레드 프로그래밍

스레드 개요스레드 개요 (11)(11)

13Mobile Programming

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[ 예제 6-4] ThreadCanvas.java

Page 14: 스레드 프로그래밍

스레드 개요스레드 개요 (12)(12)

14Mobile Programming

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[ 예제 6-5] ThreadClass.java

Page 15: 스레드 프로그래밍

Thread Class (1)Thread Class (1)

▶ Thread 클래스의 생성자

15Mobile Programming

Page 16: 스레드 프로그래밍

Thread Class (2)Thread Class (2)

▶ Thread 클래스의 메소드

16Mobile Programming

Page 17: 스레드 프로그래밍

Thread Class (3)Thread Class (3)

▶ 스레드 상태 전이도

▶ Java.lang.Object 클래스에서 상속받은 메소드

17Mobile Programming

생성생성run(

) 실행

run( )

실행

일시정지일시정지

정지정지

new

start( )

yield( )스케줄러

wait( )notify( )

nofifyAll( )

sleep( )인터럽트

Page 18: 스레드 프로그래밍

Thread Class (4)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) { ... }

}

18Mobile Programming

•Thread t1 = new Thread(this);•Thread t2 = new Thread(this, “thread_name”);

•Thread t1 = new Thread(this);•Thread t2 = new Thread(this, “thread_name”);

Page 19: 스레드 프로그래밍

Thread Class (5)Thread Class (5)

▶ 스레드 상태 검사

▷ 현재 스레드가 살아있는지 확인 살아있는 상태 : true 반환 종료 : false 반환

19Mobile Programming

•public final boolean isAlive( )•public final boolean isAlive( )

Page 20: 스레드 프로그래밍

Thread Class (6)Thread Class (6)

▶ 스레드 우선 순위

▷ 우선 순위 설정 및 확인 setPriority( ) 메소드 getPriority( ) 메소드

Thread.currentThread( ).setPriority(Thread.NORM_PRIORITY+2);

t1.setPriority(7);Thread.currentThread().getPriority( );

20Mobile Programming

•Thread.MIN_PRIORITY : 최소 우선순위 값 (=1)•Thread.NORM_PRIORITY : 기본 우선순위 값 (=5)•Thread.MAX_PRIORITY : 최대 우선순위 값 (=10)

•Thread.MIN_PRIORITY : 최소 우선순위 값 (=1)•Thread.NORM_PRIORITY : 기본 우선순위 값 (=5)•Thread.MAX_PRIORITY : 최대 우선순위 값 (=10)

Page 21: 스레드 프로그래밍

Thread Class (7)Thread Class (7)

▶ 스레드 기본 상태 전이▷ 스레드 실행을 일시적으로 정지했다가 다시 실행시키는

메소드 sleep( ), join( ), yield( )

▶ sleep( )

▶ 사용 예

21Mobile Programming

static void sleep(long millis)throws InterruptedException

static void sleep(long millis)throws InterruptedException

try {Thread.sleep((int)(1000));

} catch (InterruptedException e) {

System.out.println(e);}

Page 22: 스레드 프로그래밍

Thread Class (8)Thread Class (8)

▶ join( )▷ 호출한 스레드를 종료할 때까지 현재 스레드를 기다림

▶ yield( )▷ 우선순위가 같은 실행 가능 상태에 있는 다른 스레드를

수행하도록 CPU 를 양보

22Mobile Programming

public final void join( )throws InterruptedException

public final void join( )throws InterruptedException

public static void yield( )public static void yield( )

Page 23: 스레드 프로그래밍

Thread Class (9)Thread Class (9)

▶ 멀티 스레드▷ 하나의 자원을 공유하면서 여러 작업을 동시 수행

▶ 두 스레드 간에 발생할 수 있는 문제점▷ 자원 공유에 따른 상호배제 (Mutual Exclusion)

▷ 해결 방법으로 스레드 동기화 기능을 제공23Mobile Programming

Page 24: 스레드 프로그래밍

Thread Class (10)Thread Class (10)

▶ 동기화로 두 스레드 간의 문제점 해결

▷ synchronized 키워드를 사용해 임계 영역 설정▷ 예제 6-6 참조

24Mobile Programming

Page 25: 스레드 프로그래밍

스레드 실전 프로그래밍스레드 실전 프로그래밍 (1)(1)

▶ 별 애니메이션 프로그램▷ 초기화면 : 별 하나 등장

임의의 방향으로 이동 상하 좌우 벽면에 부딪치면 튕겨져 다른 방향으로 이동

▷ 우측 버튼을 클릭하면 : 별이 하나씩 증가▷ 좌측 버튼을 클릭하면 : 별이 하나씩 감소▷ 상하 버튼을 클릭하면 : 별의 속도 증 , 감

25Mobile Programming

Page 26: 스레드 프로그래밍

스레드 실전 프로그래밍스레드 실전 프로그래밍 (2)(2)

▶ 프로그램 구성도▷ ThreadStarMIDlet 클래스▷ ThreadStarCanvas 클래스▷ ThreadStarClass 클래스

▷ 예제 6-7 ~6-9 참조

26Mobile Programming

MidletMidlet CanvasCanvas ThreadThread

ThreadS

ThreadStarMIDlet()

starApp( )pauseApp( )

destroyApp( )

ThreadS

ThreadStarMIDlet()

starApp( )pauseApp( )

destroyApp( )

ThreadStarCanvas( )

Paint( )keyPressed( )

ThreadStarCanvas( )

Paint( )keyPressed( )

ThreadStarClass( )

setStarPaint( )slower( )faster( )

ThreadStarClass( )

setStarPaint( )slower( )faster( )

ThreadStarMIDlet

ThreadStarMIDlet

ThreadStarCanvas

ThreadStarCanvas ThreadStarClassThreadStarClass

1 1 1 n

Page 27: 스레드 프로그래밍

스레드 실전 프로그래밍스레드 실전 프로그래밍 (3)(3)

27Mobile Programming

01 import javax.microedition.midlet.*;02 import javax.microedition.lcdui.*;0304 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

[ 예제 6-7] ThreadStarMIDlet.java

Page 28: 스레드 프로그래밍

스레드 실전 프로그래밍스레드 실전 프로그래밍 (4)(4)

28Mobile Programming

…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();23}

[ 예제 6-8] ThreadStarCanvas.java

[ 예제 6-8] ThreadStarCanvas.java

Page 29: 스레드 프로그래밍

스레드 실전 프로그래밍스레드 실전 프로그래밍 (5)(5)

29Mobile Programming

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);30}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

[ 예제 6-8] ThreadStarCanvas.java

Page 30: 스레드 프로그래밍

스레드 실전 프로그래밍스레드 실전 프로그래밍 (6)(6)

30Mobile Programming

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

[ 예제 6-8] ThreadStarCanvas.java

Page 31: 스레드 프로그래밍

스레드 실전 프로그래밍스레드 실전 프로그래밍 (7)(7)

31Mobile Programming

...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;22 deltaY = random.nextInt() & 1;

[ 예제 6-9] ThreadStarclass.java

[ 예제 6-9] ThreadStarclass.java

Page 32: 스레드 프로그래밍

스레드 실전 프로그래밍스레드 실전 프로그래밍 (8)(8)

32Mobile Programming

23 try {24 star_image = Image.createImage("/star.png");25 } catch(Exception e) {26 System.out.println("Image Loading Fail");27 }28}29 public void run() {30 System.out.println("getName= " + Thread.currentThread().getName());31 int right = left + width;32int 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

[ 예제 6-9] ThreadStarclass.java

Page 33: 스레드 프로그래밍

스레드 실전 프로그래밍스레드 실전 프로그래밍 (9)(9)

33Mobile Programming

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

[ 예제 6-9] ThreadStarclass.java