PowerPoint Presentation

Similar documents
제11장 프로세스와 쓰레드

Microsoft PowerPoint - lec12 [호환 모드]

쉽게 풀어쓴 C 프로그래밍

PowerPoint Presentation

PowerPoint Presentation

스레드의우선순위 우선순위설정메소드 : void setpriority(int newpriority) newpriority 에설정할수있는등급 : 1( 가장낮은우선순위 ) 부터 10( 가장높은우선순위 ) 가장높은우선순위 : MAX_PRIORITY, 보통우선순위 : NORM_

PowerPoint Presentation

JAVA PROGRAMMING 실습 08.다형성

PowerPoint Presentation

PowerPoint Presentation

스레드를적용하지않은결과와스레드를적용한결과의비교 1) 두개의작업을스레드를사용하지않고수행한예 ) : 순차작업 class ThreadTest2 { System.out.print("-");// 화면에 - 를출력하는작업 System.out.print(" ");// 화면에 를출력

Design Issues

PowerPoint Presentation

(Microsoft PowerPoint - java2-lecture6.ppt [\310\243\310\257 \270\360\265\345])

JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 ( ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각

슬라이드 1

PowerPoint Presentation

q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2

PowerPoint Presentation

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

Microsoft PowerPoint - 2강

Microsoft PowerPoint - java2-lecture6.ppt [호환 모드]

JAVA PROGRAMMING 실습 09. 예외처리

PowerPoint Presentation

Cluster management software

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

02 C h a p t e r Java

비긴쿡-자바 00앞부속

PowerPoint 프레젠테이션

gnu-lee-oop-kor-lec06-3-chap7

PowerPoint 프레젠테이션

Microsoft PowerPoint - CSharp-10-예외처리

Microsoft PowerPoint - Java7.pptx

(Microsoft PowerPoint - java1-lecture11.ppt [\310\243\310\257 \270\360\265\345])

Network Programming

Microsoft PowerPoint 자바-기본문법(Ch2).pptx

JAVA PROGRAMMING 실습 05. 객체의 활용

쉽게 풀어쓴 C 프로그래밍

PowerPoint 프레젠테이션

Microsoft PowerPoint - 04-UDP Programming.ppt

PowerPoint Presentation

JAVA PROGRAMMING 실습 07. 상속

PowerPoint 프레젠테이션

Microsoft PowerPoint - RMI.ppt

Java ~ Java program: main() class class» public static void main(string args[])» First.java (main class ) /* The first simple program */ public class

JUNIT 실습및발표

PowerPoint Presentation

No Slide Title

10.0pt1height.7depth.3width±â10.0pt1height.7depth.3widthÃÊ10.0pt1height.7depth.3widthÅë10.0pt1height.7depth.3width°è10.0pt1height.7depth.3widthÇÁ10.0pt1height.7depth.3width·Î10.0pt1height.7depth.3width±×10.0pt1height.7depth.3width·¡10.0pt1height.7depth.3width¹Ö pt1height.7depth.3widthŬ10.0pt1height.7depth.3width·¡10.0pt1height.7depth.3width½º, 10.0pt1height.7depth.3width°´10.0pt1height.7depth.3widthü, 10.0pt1height.7depth.3widthº¯10.0pt1height.7depth.3width¼ö, 10.0pt1height.7depth.3width¸Þ10.0pt1height.7depth.3width¼Ò10.0pt1height.7depth.3widthµå

교육자료

PowerPoint 프레젠테이션

JMF3_심빈구.PDF

rmi_박준용_final.PDF

(8) getpi() 함수는정적함수이므로 main() 에서호출할수있다. (9) class Circle private double radius; static final double PI= ; // PI 이름으로 로초기화된정적상수 public

5장.key

Java

PowerPoint Presentation

PowerPoint Template

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

PowerPoint 프레젠테이션

PowerPoint Presentation

예외 예외정의예외발생예외처리예외전파 단정 단정의선언 단정조건검사옵션 2

쉽게

Spring Data JPA Many To Many 양방향 관계 예제

. 스레드 (Thread) 란? 스레드를설명하기전에이글에서언급되는용어들에대하여알아보도록하겠습니다. - 응용프로그램 ( Application ) 사용자에게특정서비스를제공할목적으로구현된응용프로그램을말합니다. - 컴포넌트 ( component ) 어플리케이션을구성하는기능별요

Microsoft PowerPoint - C++ 5 .pptx

예제 2) Test.java class A intvar= 10; void method() class B extends A intvar= 20; 1"); void method() 2"); void method1() public class Test 3"); args) A

Java ...

Microsoft PowerPoint - Supplement-03-TCP Programming.ppt [호환 모드]

Microsoft PowerPoint - Lect04.pptx

PowerPoint Presentation

쉽게 풀어쓴 C 프로그래밍

Microsoft PowerPoint - 03-TCP Programming.ppt

Microsoft Word - java19-1-midterm-answer.doc

TEST BANK & SOLUTION

C++ Programming

9장.예외와 단정

ch09

4장.문장

JAVA PROGRAMMING 실습 02. 표준 입출력

오버라이딩 (Overriding)

쉽게 풀어쓴 C 프로그래밊

PowerPoint Presentation

<4D F736F F F696E74202D20C1A63234C0E520C0D4C3E2B7C228B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

자바 프로그래밍

PowerPoint Template

Chap12

Semantic Consistency in Information Exchange

1. 객체의생성과대입 int 형변수 : 선언과동시에초기화하는방법 (C++) int a = 3; int a(3); // 기본타입역시클래스와같이처리가능 객체의생성 ( 복습 ) class CPoint private : int x, y; public : CPoint(int a

12-file.key

<C0DAB9D920B8F1C2F72E687770>

Spring Boot/JDBC JdbcTemplate/CRUD 예제

쉽게 풀어쓴 C 프로그래밍

Microsoft Word - EEL2 Lab4.docx

A Tour of Java V

슬라이드 1

PowerPoint Presentation

Spring Boot

05-class.key

Transcription:

public class SumTest { public static void main(string a1[]) { int a, b, sum; a = Integer.parseInt(a1[0]); b = Integer.parseInt(a1[1]); sum = a + b ; // 두수를더하는부분입니다 System.out.println(" 두수의합은 " + sum + " 입니다 "); 1

학습목표 스레드의개념과스레드생명주기에관해학습한다. 스레드생성방법에관해학습한다. 스레드의우선순위에관해학습한다. 다중스레드의시작과종료에관해학습한다. 다중스레드의사용방법에관해학습한다. 스레드사이의통신방법에관해학습한다. 2

목차 section 1 스레드개요 section 2 Thread 클래스와스레드생명주기 section 3 스레드의생성과사용 - 3-1 Thread 클래스이용 - 3-2 Runnable 인터페이스이용 section 4 스레드우선순위 section 5 스레드의시작과종료 section 6 스레드동기화 (Synchronization) section 7 스레드사이의통신 3

1 스레드개요 다중스레드 (multi thread) - 하나의프로그램내에서다수개의스레드가동시에수행되는형태 다수개의 CPU 를가진컴퓨터에서다중스레드의실행 307 page 4

1 스레드개요 한개의 CPU 를가진컴퓨터에서다중스레드의실행 307 page 5

2 Thread 클래스와스레드생명주기 Thread 클래스 - java.lang 패키지에라이브러리클래스로제공 형식 Thread() Thread(String s) Thread(Runnable r) Thread(Runnable r, String s) 6

2 Thread 클래스와스레드생명주기 스레드클래스의메소드 메소드 이름설명 static void sleep(long msec) throws InterruptedException static void sleep(long msec, int nsec) throws InterruptedException String getname() void setname(string s) void start() final int getpriority() final void setpriority(int p) boolean isalive() void join() throws InterruptedException msec에지정된밀리초 (milliseconds) 동안대기 msec에지정된밀리초 +nsec에지정된나노초 (nanoseconds) 동안대기스레드의이름을반환스레드의이름을 s로설정스레드를시작시킨다. run() 메소드를호출스레드의우선순위를반환스레드의우선순위를 p 값으로설정스레드가실행가능상태, 실행상태, 대기상태에있으면 true를그렇지않으면 false를반환스레드가끝날때까지대기 void run() 스레드가실행할부분을기술하는메소드. 하위클래스에서오버라이딩되어야한다. void suspend() 스레드가일시정지된다. resume() 에의해다시시작될수있다. void resume() 일시정지된스레드를다시시작시킨다. 7

2 Thread 클래스와스레드생명주기 스레드의생명주기 310 page 8

3 스레드의생성과사용 3-1 Thread 클래스이용 Thread(java.lang.Thread) 클래스로부터직접상속받아스레드특징을가 지는클래스를생성하여스레드를사용하는방법 class ThreadA extends Thread {... public void run() {...... Thread 클래스로부터상속 상위클래스인 Thread 클래스의 run() 메소드를오버라이딩하여스레드가수행하여야하는문장들을기술한다. ThreadA ta = new ThreadA(); ta.start(); 9

3 스레드의생성과사용 3-2 Runnable 인터페이스이용 스레드의특성을가져야하는클래스가이미다른클래스로부터상속을받고 있다면 Runnable 인터페이스를이용 public interface Runnable { public void run(); class RunnableB extends Applet implements Runnable {... public void run() {...... Runnable 인터페이스에정의된 run() 메소드를오버라이딩하여스레드가수행할문장들을기술한다. 10

3 스레드의생성과사용 3-2 Runnable 인터페이스이용 인터페이스를이용하여생성된클래스로부터스레드객체를생성하는예 RunnableB rb = new RunnableB(); Thread tb = new Thread(rb); tb.start(); 스레드시작 객체 rb 생성 rb 를매개변수로하여스레드객체 tb 를생성 RunnableB rb = new RunnableB(); new Thread(rb).start(); 스레드객체를생성하여바로시작 11

3 스레드의생성과사용 3-2 Runnable 인터페이스이용 실습예제 ThreadFromThread.java 01 02 03 04 05 06 07 08 09 10 11 12 13 class ThreadTest extends Thread { public void run() { for (int i=1 ; i<=10 ; i++) { System.out.println(" 재미있는자바 :" + i); public class ThreadFromThread { public static void main(string args[]) { ThreadTest t = new ThreadTest(); t.start(); 스레드시작 (run() 메소드호출 ) Thread 클래스로부터상속받아클래스작성 run() 메소드오버라이딩 스레드특성을가진객체생성 12

3 스레드의생성과사용 3-2 Runnable 인터페이스이용 13

3 스레드의생성과사용 3-2 Runnable 인터페이스이용 실습예제 ThreadFromRunnable.java 01 02 03 04 05 06 07 08 09 10 11 12 13 14 class RunnableTest implements Runnable { public void run() { for (int i=1 ; i<=10 ; i++) { System.out.println(" 재미있는자바 :" + i); public class ThreadFromRunnable { public static void main(string args[]) { RunnableTest r = new RunnableTest(); Thread t = new Thread(r); t.start(); 스레드시작 (run() 메소드호출 ) Runnable 인터페이스를포함하는클래스작성 run() 메소드오버라이딩 객체생성 생성된객체를이용하여스레드객체생성 14

3 스레드의생성과사용 3-2 Runnable 인터페이스이용 15

3 스레드의생성과사용 3-2 Runnable 인터페이스이용 실습예제 DoubleThread.java 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 class ThreadTest1 extends Thread { public ThreadTest1(String str) { setname(str); public void run() { for (int i=1 ; i<=10 ; i++) { System.out.println(i + getname()); System.out.println(" 끝 " + getname()); public class DoubleThread { public static void main(string args[]) { ThreadTest1 t1 = new ThreadTest1 (" : 배우기쉬운자바 "); ThreadTest1 t2 = new ThreadTest1 (" : 배우기어려운자바 "); t1.start(); 스레드동시실행 t2.start(); 스레드동시실행 스레드의이름을설정 Thread 클래스로부터상속받아클래스작성 번호와스레드이름을출력 이름이다른두개의스레드객체생성 16

3 스레드의생성과사용 3-2 Runnable 인터페이스이용 실행결과 1 17

3 스레드의생성과사용 3-2 Runnable 인터페이스이용 실행결과 2 18

4 스레드우선순위 스레드에우선순위를부여하여우선순위가높은스레드에실행의우선권을 주어실행 setpriority() - Thread 클래스에는스레드에우선순위를부여하는메소드가제공 static final int MAX_PRIORITY 우선순위값으로 10을가진다. static final int MIN_PRIORITY 우선순위값으로 1을가진다. static final int NORM_PRIORITY 우선순위값으로 5를가진다. 19

4 스레드우선순위 실습예제 ThreadPriority.java 01 02 03 04 05 06 07 08 09 10 11 class PriorityTest extends Thread{ public PriorityTest(String str){ setname(str); public void run(){ for(int i=1; i<=5; i++){ System.out.println( i + getname() + " 우선순위 : " + getpriority() ); getpriority() 메소드로우선순위출력 20

4 스레드우선순위 실습예제 ThreadPriority.java 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 class ThreadPriority { public static void main(string args[]){ PriorityTest t1 = new PriorityTest(" : 첫번째스레드 "); PriorityTest t2 = new PriorityTest(" : 두번째스레드 "); PriorityTest t3 = new PriorityTest(" : 세번째스레드 "); int priority_t1 = Integer.parseInt(args[0]); int priority_t2 = Integer.parseInt(args[1]); t1.setpriority(priority_t1); t2.setpriority(priority_t2); t3.setpriority(thread.min_priority); t1.start(); t2.start(); t3.start(); 우선순위설정 21

4 스레드우선순위 22

5 스레드의시작과종료 다중스레드를가진프로그램의실행흐름 323 page 23

5 스레드의시작과종료 실습예제 DoubleThread1.java 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 class DoubleThreadTest1 extends Thread { public DoubleThreadTest1(String str) { setname(str); public void run() { for (int i=1 ; i<=3 ; i++) { System.out.println(i + getname()); System.out.println(" 끝 " + getname()); public class DoubleThread1 { public static void main(string args[]) { DoubleThreadTest1 t1 = new DoubleThreadTest1(" : 배우기쉬운자바 "); DoubleThreadTest1 t2 = 24

5 스레드의시작과종료 실습예제 DoubleThread1.java 17 18 19 20 21 22 23 new DoubleThreadTest1(" : 배우기어려운자바 "); System.out.println("***** 스레드시작전 *****"); t1.start(); t2.start(); System.out.println("***** 스레드종료후 *****"); 스레드시작전에출력 25

5 스레드의시작과종료 26

5 스레드의시작과종료 실습예제 DoubleThread2.java 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 class DoubleThreadTest2 extends Thread { public DoubleThreadTest2(String str) { setname(str); public void run() { for (int i=1 ; i<=3 ; i++) { System.out.println(i + getname()); System.out.println(" 끝 " + getname()); public class DoubleThread2 { public static void main(string args[])throws Exception { DoubleThreadTest2 t1 = new DoubleThreadTest2 (" : 배우기쉬운자바 "); DoubleThreadTest2 t2 = new DoubleThreadTest2 join() 메소드사용을위해예외처리 27

5 스레드의시작과종료 실습예제 DoubleThread1.java 17 (" : 배우기어려운자바 "); 18 System.out.println("***** 스레드시작전 *****"); 19 t1.start(); 20 t2.start(); 21 22 t1.join(); t2.join(); join() 메소드수행 23 24 System.out.println("***** 스레드종료후 *****"); 스레드종료후에실행 25 28

5 스레드의시작과종료 29

6 스레드동기화 (Synchronization) 임계영역 (critical section) - 다수개의스레드가접근가능한영역 - 한순간에는하나의스레드만사용할수있는영역 자바에서는임계영역지정을위한 synchronized 메소드를제공 30

6 스레드동기화 (Synchronization) 다중스레드환경에서의 synchronized 메소드실행 329 page 31

6 스레드동기화 (Synchronization) 실습예제 330 page 32

6 스레드동기화 (Synchronization) 실습예제 TVContribution.java 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 class Account { private int total = 0; synchronized void deposit() { 1000원을더하는동기화메소드선언 total = total + 1000; int gettotal() { return total; class Customer extends Thread { Account same_a; Customer(Account a, String s) { same_a = a; 스레드이름과 Account 객체를설정 setname(s); public void run() { for(int i = 0; i < 200 ; i++) { System.out.println(getName() + " : " + i +" 번째 "); 33

6 스레드동기화 (Synchronization) 실습예제 TVContribution.java 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 same_a.deposit(); if (same_a.gettotal() >= 500000) break; public class TVContribution { public static void main(string args[])throws Exception { Account same_account = new Account(); Customer donator1 = new Customer(same_account,"1번째성금자 "); Customer donator2 = new Customer(same_account,"2번째성금자 "); Customer donator3 = new Customer(same_account,"3번째성금자 "); Customer donator4 = new Customer(same_account,"4번째성금자 "); Customer donator5 = new Customer(same_account,"5번째성금자 "); 반복문을돌며 deposit() 메소드호출 전체금액이 50 만원보다크면반복문을벗어남 Account 클래스로부터객체생성 생성자에서동일한객체를지정함 (5 개의스레드가 same_account 객체공유 ) 34

6 스레드동기화 (Synchronization) 실습예제 TVContribution.java 37 38 39 40 41 42 43 44 45 46 47 48 49 50 donator1.start(); donator2.start(); donator3.start(); donator4.start(); donator5.start(); donator1.join(); donator2.join(); donator3.join(); donator4.join(); donator5.join(); System.out.println(" 성금총액은 : " + same_account.gettotal()); 35

6 스레드동기화 (Synchronization) 실행결과 36

6 스레드동기화 (Synchronization) 실행결과 37

7 스레드사이의통신 스레드사이의통신을위한메소드를 java.lang.object 클래스에제공 Object 클래스에서제공되는메소드중 wait(), notify(), notifyall() 메소드 가스레드사이의통신에이용 wait() 메소드의 3 가지형태 void wait() throws InterruptedException void wait(long msec) throws InterruptedException void wait(long msec, int nsec) throws InterruptedException 38

7 스레드사이의통신 wait() : 무한정대기상태에들어가는메소드 wait(long msec) : msec 밀리초동안대기하다스스로깨어나는메소드 wait(long msec, int nsec) : msec 밀리초와 nsec 나노초동안대기하다스스로깨어나는메소드 notify() : 대기중인스레드가여러개일경우그중에하나의스레드만을깨운 notifyall() 메소드 : 대기중인모든스레드를깨우는것을제외하고는 notify() 와같음 void notify() void notifyall() 39

7 스레드사이의통신 wait( ) 메소드와 notify( ), notifyall( ) 메소드의작동 335 page 40

7 스레드사이의통신 예제 ProducerConsumer.java 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 class Buffer { private int contents; private boolean available = false; public synchronized void put(int value) { while (available == true ) { try{ wait(); catch (InterruptedException e) { contents = value; System.out.println (" 생산자 ########## : 생산 " + contents); notify(); available = true; public synchronized int get() { while (available == false ) { try { wait(); 생산자와소비자가공유하는데이터 ( 쌀 ) 를넣는곳 번갈아가며수행하기위한이진변수 생산자가가져다놓는동기화메소드 이진변수의값에따라대기여부결정 데이터를생산하고대기스레드를깨운다 소비자가데이터를가져가는동기화메소드 이진변수의값에따라대기여부결정 41

7 스레드사이의통신 예제 ProducerConsumer.java 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 catch (InterruptedException e) { System.out.println (" 소비자 ########## : 소비 " + contents); notify(); available = false; return contents; class Producer extends Thread { private Buffer b; public Producer(Buffer blank) { b = blank ; public void run() { for (int i = 1; i <= 10;i++) b.put(i); 값을가져오고대기스레드를깨운다 생산자와스레드클래스 42

7 스레드사이의통신 예제 ProducerConsumer.java 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 class Consumer extends Thread { private Buffer b; public Consumer(Buffer blank) { b = blank; public void run() { int value = 0; for (int i = 1 ; i <= 10 ; i++ ) value = b.get(); public class ProducerConsumer { public static void main(string args[]) { Buffer buff = new Buffer(); Producer p1 = new Producer(buff); Consumer c1 = new Consumer(buff); p1.start() ; c1.start() ; 소비자스레드클래스 하나의 Buffer 객체생성 동일한 Buffer 객체를사용하여스레드객체생성 43

7 스레드사이의통신 실행결과 44

학습정리 스레드개요 1 스레드는실행중인프로세스라할수있으며, 하나의프로그램에다수개의스레드를실행시킬수있다. 2 한개의 CPU를가진컴퓨터에서스레드는 CPU에의해돌아가며수행되게된다. Thread 클래스와스레드생명주기 1 자바에서는스레드를지원하기위해 Thread 클래스를제공하고있다. 2 스레드클래스는스레드를지원하는다양한메소드를가지고있다. 3 스레드는생성, 실행가능상태, 실행상태, 대기상태등의생명주기를가지고있다. 스레드의생성과사용 1 자바에서스레드는두가지방법으로사용이가능하다. 45

학습정리 2 Thread 클래스로부터상속받아스레드를사용하는방법과 Runnable 인터페이스를포함하여스레드클래스를사용하는방법이있으며, 현재의클래스가다른클래스로부터이미상속을받고있는경우에 Runnable 인터페이스를이용하여스레드를작성한다. 스레드의우선순위 1 각각의스레드는 1~10 사이의우선순위를가질수있다. 2 CPU 는실행가능상태의스레드중에서우선순위가높은스레드를먼저수행한다. 스레드의시작과종료 1 다중스레드를가진프로그램에서 start() 메소드에의해스레드가시작되면, 프로그램의흐름이단일흐름에서다중흐름으로전환된다. 2 다중스레드는동시수행되는개념이므로스레드가수행을마치고다시단일흐름으로프로그램을실행시키기위해서는 join() 메소드를이용하여흐름을하나로만들어야한다. 46

학습정리 스레드동기화 1 다수개의스레드가임계영역을수행하기위해서는 synchronized 메소드를사용해야한다. 2 synchronized 메소드는한순간에하나의스레드만실행할수있다. 3 한스레드가동기화메소드를수행중이면다른스레드는대기해야한다. 스레드사이의통신 1 스레드사이의통신을위해 wait(), notify(), notifyall() 메소드가사용되며, 이러한메소드는 Object 클래스에제공하고있다. 2 notify() 메소드는대기상태에있는스레드를깨우는역할을한다. 47

48