스레드 프로그래밍 Lecture #7.

Slides:



Advertisements
Similar presentations
Java 2D Training. Basic Tools Java SDK 1.4x Wireless Toolkit 2.x NetBeans IDE + mobility pack Global Code editor Text Comparer Tools Graphics Editor Sprite.
Advertisements

CS4273: Distributed System Technologies and Programming I Lecture 4: Java Threads and Multithread Programming.
10. Multithreading 1 public class SumTest { public static void main(String a1[]) public static void main(String a1[]) { int a, b, sum; int a, b, sum; a.
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Albert Johnson Molly Richardson Andrew Kruth.  Threads Runnable interface sleep()  GUIs repaint() paintComponent()
G52CON: Concepts of Concurrency Lecture 2 Processes & Threads Chris Greenhalgh School of Computer Science
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Unit 151 Threads II Thread Priorities The interrupt() method Threads Synchronization Thread Animation Examples – after each section Exercises.
Starts to load image Delay on network Load some more of the image Time for some word processing Thread 2 Thread 1 Figure 15.1 Two threads sharing the processor.
Unit 161 Further Threads Programming Some Terminologies on Multithreading Example 1: Threads Synchronization Example 2: ‘Salaam Shabab’ Animation Example.
Definitions Process – An executing program
1 Threads (Part II) Threads and Concurrency (Part II) Overview  Review of Previous Lecture.  Controlling Threads and Thread State.  Example 1: Creating.
Threads Just Java: C10–pages 251- C11–pages 275-
Lecture 4 : JAVA Thread Programming
J2ME: M3G/11 Intro to J2ME. Prog. v Objectives: –to introduce M3G; –to start talking about "M3G Chapter 2. An Animated Model" u leave the floor,
SOAP 실전예제 Internet Computing KUT Youn-Hee Han.
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Cs3180 (Prasad)L11Threads1 Concurrent Programming class Thread interface Runnable class Object.
University of Sunderland Java Threading, Mutex and Synchronisation Lecture 02 COMM86 Concurrent and Distributed Software Systems.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Online Appointment Book Implement a Client/Server application for an online appointment book. Client should be a Graphical User Interface application.
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
1/43 고급자바프로그래밍 (ADVANCED JAVA PROGRAMMING) 강원대학교 컴퓨터학부 2012 년 가을학기 담당교수 정충교 1.
Threads.
User Interface Summary Displayable ScreenCanvas FormAlertListTextbox Item DateFieldImageItemTextFieldStringItemGaugeChoiceGroup.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
1 5.0 Garbage collector & Threads : Overview Introduction: In this module we discuss the merits and demerits of automated garbage collection over manual.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
Threading and Concurrency COM379T John Murray –
Packages Packages are containers for classes that are used to keep the class name space compartmentalized.. You can define classes inside a package that.
모바일 자바 프로그래밍 MIDP RMS Ps lab 오민경. MIDP RMS  RMS (Record Management System)  MIDP 에서 정의하는 영속성을 지닌 자체 데이터 저장 공간  Record Store 의 집합으로 구성된 아주 간단한 데이터베이스.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
6.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts with Java – 8 th Edition Module 6: Process Synchronization Codes.
Parallel Processing (CS526) Spring 2012(Week 8).  Shared Memory Architecture  Shared Memory Programming & PLs  Java Threads  Preparing the Environment.
1/70 강원대학교 14 주 멀티쓰레딩 Multithreading. 2/70 Process and Thread 강원대학교
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading and Garbage Collection Session 16.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
실전 이미지 처리 프로그래밍 Lecture #10. 강의 목차 ▶ 실제 게임을 구현하는 데 필요한 화면 구성을 알아본다. ▶ Canvas 클래스와 Graphics 클래스를 이용해 가장 기본적인 게임 화면을 하나씩 직접 구현해 본다. 2Mobile Programming.
방명록 제작. 목차  기본 레이아웃  DB 구조  방명록 구조  코드 설명  화면 설명.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
CHAP 14. 프로세스와 스레드. © 2012 생능출판사 All rights reserved 다중 스레딩 하나의 애플리케이션이 동시에 여러 가지 작업을 하 는 것 이들 작업은 스레드 (thread) 라고 불린다.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Java Applets Adding Animation. Import Files You still need to include the same files: –import java.applet.*; –import java.awt.*;
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
Threads in Java 1 OOutline Introduction Class Thread : An Overview of the Thread Methods Thread States: Life Cycle of a Thread Thread Priorities and Thread.
게임 API 프로그래밍 Lecture #12. 강의 목차 ▶ 모바일 게임 프로그래밍에 필요한 게임 API 의 개념을 이해 한다. ▶ 주요 게임 API 의 종류와 기본 사용법을 익힌다. ▶ 게임 API 를 이용해 실제 게임 동작을 직접 구현해 본다. 2Mobile Programming.
J2ME Programming. Java2 Micro edition Introduction 년 5 월 26 일 CLDC, MIDP 라이브러리 Reference :
Multithreading / Concurrency
Chapter 13: Multithreading
Multi Threading.
Multithreading.
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Kjava Programming.
null, true, and false are also reserved.
Java Based Techhnology
Principles of Software Development
Shane Cantrell Zach Crisman
برنامه‌نویسی چندنخی Multi-Thread Programming
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

스레드 프로그래밍 Lecture #7

강의 목차 스레드 개념을 이해한다. Thread 클래스에서 제공하는 메소드의 종류와 기능을 알아본다. 스레드를 생성하고 실행하는 방법을 알아본다. 멀티 스레드 개념을 이해하고, 동기화 방법을 익힌다 . Mobile Programming

스레드 개요 (1) 스레드(Thread)란? 생각해 봅시다! 한 프로그램 내에서 독립적으로 동작하는 일의 실행 단위 한 프로그램 내에 여러 개의 스레드를 생성, 실행 가능 생각해 봅시다! paint() 메서드를 반복시키기 위한 방법? 명령어 버튼을 클릭 : 불연속 while , for, do while 문 이용 : X 스레드 이용 Mobile Programming

[예제 6-1] ClipAniThreadMIDlet.java 스레드 개요 (2) 스레드 이용 방법 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 Mobile Programming

[예제 6-2] ClipAniThreadCanvas.java 스레드 개요 (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 인터페이스를 이용한 방법 Thread 클래스를 이용한 방법 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 클래스 private Display display; 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

[예제 6-3] ThreadMIDlet.java 스레드 개요 (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

[예제 6-4] ThreadCanvas.java 스레드 개요 (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

[예제 6-5] ThreadClass.java 스레드 개요 (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( ) 실행 일시정지 정지 new start( ) yield( ) 스케줄러 wait( ) notify( ) nofifyAll( ) sleep( ) 인터럽트 Mobile Programming

Thread Class (4) 스레드 생성 Thread t1 = new Thread(this); 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) 스레드 상태 검사 public final boolean isAlive( ) 현재 스레드가 살아있는지 확인 살아있는 상태: true 반환 종료: false 반환 public final boolean isAlive( ) Mobile Programming

Thread Class (6) 스레드 우선 순위 Thread.MIN_PRIORITY : 최소 우선순위 값(=1) 우선 순위 설정 및 확인 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( ) 사용 예 스레드 실행을 일시적으로 정지했다가 다시 실행시키는 메소드 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( ) public final void 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) 동기화로 두 스레드 간의 문제점 해결 예제 6-6 참조 synchronized 키워드를 사용해 임계 영역 설정 예제 6-6 참조 Mobile Programming

스레드 실전 프로그래밍 (1) 별 애니메이션 프로그램 초기화면: 별 하나 등장 우측 버튼을 클릭하면 : 별이 하나씩 증가 초기화면: 별 하나 등장 임의의 방향으로 이동 상하 좌우 벽면에 부딪치면 튕겨져 다른 방향으로 이동 우측 버튼을 클릭하면 : 별이 하나씩 증가 좌측 버튼을 클릭하면 : 별이 하나씩 감소 상하 버튼을 클릭하면: 별의 속도 증, 감 Mobile Programming

스레드 실전 프로그래밍 (2) 프로그램 구성도 ThreadStarMIDlet 클래스 ThreadStarCanvas 클래스 ThreadStarClass 클래스 예제 6-7 ~6-9 참조 Midlet Canvas Thread ThreadS ThreadStarMIDlet() starApp( ) pauseApp( ) destroyApp( ) ThreadStarCanvas( ) Paint( ) keyPressed( ) ThreadStarClass( ) setStarPaint( ) slower( ) faster( ) ThreadStarMIDlet ThreadStarCanvas ThreadStarClass 1 1 1 n Mobile Programming

[예제 6-7] ThreadStarMIDlet.java 스레드 실전 프로그래밍 (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

[예제 6-8] ThreadStarCanvas.java 스레드 실전 프로그래밍 (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

[예제 6-8] ThreadStarCanvas.java 스레드 실전 프로그래밍 (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-8] ThreadStarCanvas.java 스레드 실전 프로그래밍 (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

[예제 6-9] ThreadStarclass.java 스레드 실전 프로그래밍 (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

[예제 6-9] ThreadStarclass.java 스레드 실전 프로그래밍 (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

[예제 6-9] ThreadStarclass.java 스레드 실전 프로그래밍 (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