Presentation is loading. Please wait.

Presentation is loading. Please wait.

10장 다중 스레드 10.1 스레드 개요 10.2 Thread 클래스 10.3 스레드 생성

Similar presentations


Presentation on theme: "10장 다중 스레드 10.1 스레드 개요 10.2 Thread 클래스 10.3 스레드 생성"— Presentation transcript:

1 10장 다중 스레드 10.1 스레드 개요 10.2 Thread 클래스 10.3 스레드 생성
10.4 동기화(Synchronization) 10.5 스레드 사이의 통신

2 10.1 스레드 개요 프로세스 : 실행중인 프로그램 스레드 순차적으로 동작하는 문장들의 단일 집합
경량(lightweight) 프로세스 다중 스레드 하나의 프로세스(프로그램)에 하나 이상의 스레드를 생성하여 실행할 때 자바는 스레드를 지원하기 위해 java.lang.Thread 클래스 제공

3 스레드 개요 - 다중 스레드 두개의 스레드 하나의 프로그램

4 스레드 개요 - 스레드 생명주기 스레드의 생명주기 start()
스레드는 탄생하고 소멸될 때까지 생명주기(life cycle)를 가진다 완료 실행상태 sleep(), wait(), suspend(), 입출력 등 실행가능 상태 대기 생성 start() notify(), notifyAll(), resume(), 입출력 완료 등 스레드의 생명주기

5 10.2 Thread 클래스 JDK는 스레드를 지원하는 java.lang.Thread 클래스 제공 스레드를 생성하기 위해 사용
4개의 생성자를 제공 Thread() Thread(String s) Thread(Runnable r) Thread(Runnable r, String s)

6 Thread 클래스의 메소드 void sleep(long msec) msec에 지정된 밀리초(milliseconds) 동안 대기 throws InterruptedException void sleep(long msec, int nsec) msec에 지정된 밀리초+nsec에 지정된 throws InterruptedException 나노초(nanoseconds) 동안 대기 String getName() 스레드의 이름을 반환 void setName(String s) 스레드의 이름을 s로 설정 void start() 스레드를 시작시킨다. run() 메소드를 호출 int getPriority() 스레드의 우선 순위를 반환 void setPriority(int p) 스레드의 우선 순위를 p값으로 설정 boolean isAlive() 스레드가 시작되었고 아직 끝나지 않았으면 true를 그렇지 않으면 false를 반환 void join() 스레드가 끝날 때까지 대기 void run() 스레드가 실행할 부분을 기술하는 메소드. 하위 클래스에서 오버라이딩 되어야 한다 void suspend() 스레드가 일시 정지된다. resume()에 의해 다시 시작될 수 있다. void resume() 일시 정지된 스레드를 다시 시작시킨다.

7 10.2 스레드의 생성 스레드를 생성하는 2가지 방법 Thread 클래스로부터 직접 상속받아 스레드를 생성
Runnable 인터페이스를 사용하는 방법(현재의 클래스가 이미 다른 클래스로부터 상속 받고 있는 경우)

8 스레드의 생성 - Thread 클래스 이용 Thread 클래스로부터 직접 상속 받아 스레드를 생성
Thread 클래스에서 제공되는 run() 메소드를 오버라이딩하여 스레드의 동작을 기술 class ThreadA extends Thread { // Thread 클래스로부터 상속 public void run() { .... // 상위 클래스인 Thread 클래스의 run() 메소드를 오버 .... //라 이딩하여 스레드가 수행하여야 하는 문장들을 기술 } ....… ThreadA ta = new ThreadA(); ta.start(); // 스레드 객체를 생성하여 스레드를 // 시작시킨다

9 스레드의 생성 - Runnable 인터페이스 이용
Runnable 인터페이스는 JDK에 의해 제공되는 라이브러리 인터페이스이다 Runnable 인터페이스에는 run() 메소드만 정의되어 있다 public interface Runnable { public void run(); }

10 스레드의 생성 - Runnable 인터페이스 이용
이미 Applet 클래스로부터 상속을 받고 있으므로 인터페이스 이용 class RunnableB extends Applet implements Runnable { ......… public void run() { // Runnable 인터페이스에 정의된 run() 메소드를 // 오버라이딩하여 스레드가 수행할 문장들을 기술한다 } .....…

11 스레드의 생성 - Runnable 인터페이스 이용
RunnableB rb = new RunnableB(); // 객체 rb 생성 Thread tb = new Thread(rb); // rb를 매개변수로 하여 스레드 객체 tb를 생성 tb.start(); // 스레드 시작 또는 RunnableB rb = new RunnableB(); new Thread(rb).start(); // 스레드 객체를 생성하여 바로 시작

12 예제1) 200초마다 하나의 문장씩 출력하는 예제 class ThreadTest extends Thread{ public void run(){ try{ for (int j=0;j<10;j++){ Thread.sleep(200); System.out.println(“Easy Java :”+j); } catch(InterruptedException e){ System.out.println(e); Class ThreadfromThread { public static void main(String args[]){ ThreadTest t = new ThreadTest(); t.start();

13 예제2) Runnable 인터페이스를 이용한 동일한 예제
class RunnableTest implements Runnable{ public void run(){ try{ for (int j=0;j<10;j++){ Thread.sleep(200); System.out.println(“Easy Java :”+j); } catch(InterruptedException e){ System.out.println(e); Class ThreadfromRunnable { public static void main(String args[]){ RunnableTest r = new RunnableTest(); Thread t = new Thread(r); t.start();

14 예제3) 하나의 스레드 클래스로부터 두개의 스레드 객체를 생성하는 예제
class ThreadTest extends Thread { public ThreadTest(string str){ super(str); } public void run(){ try{ for (int j=0;j<10;j++){ Thread.sleep(2); System.out.println(j+getName()); System.out.println(“끝”+getName()); catch(InterruptedException e){ System.out.println(e); Class ThreadDouble { public static void main(String args[]){ ThreadTest t1 = new ThreadTest(“ 스레드 1”); ThreadTest t2 = new ThreadTest(“ 스레드 2”); t1.start(); t2.start();

15 10.4 동기화(Synchronization)
대부분의 응용 프로그램에서 다수개의 스레드가 공유할 수 있는 부분이 요구된다 공유부분은 상호 배타적으로 사용되어야 한다 임계영역(critical section) 상호배타적으로 사용되는 공유부분 자바는 한 순간에 하나의 스레드만 실행할 수 있는 synchronized method 제공 한 스레드가 synchronized method를 수행 중이면 다른 스레드는 대기한다

16 동기화(Synchronization) - synchronized method 수행
시간 t lock을 얻는다 t lock을 요청하지만 이미 t 사용중이므로 기다린다 t3 t lock을 양보한다 t lock을 얻는다 t6 t7 t8 t lock을 양보한다 synchronized method 스레드A 스레드B ……… ……………….. 임계영역 문장들

17 예제1) 경매 시스템의 경매 DB구현, 5명이 50만원이 될 때까지 1000원씩 경쟁
class Account { private int total = 0; synchronized void deposit(int amount){ total += amount; } int gettotal(){ return total; class Customer extends Thread { Account account1; Customer(Account account){ this.account1 = account; public void run(){ try{ for (int j=0; j<200;j++){ System.out.println(“경매자 ”+getName()+” : “+j+”번째”); account1.deposit(1000); sleep(2); if (account1.gettotal() >= ) break; catch(Exception e){ System.out.println(e);

18 class Auction { public static void main(String args[]){ Account account = new Account(); Customer customers[] = new Customer[5]; for (int j=0; j<5; j++){ customers[I] = new Customer(account); customers[I].start(); } for (int j=0; j<5;j++){ try{ customers[I].join(); catch(InterruptedException e){ System.out.println(e); System.out.println(“경매 낙찰가 : “+account.gettotal());

19 10.5 스레드 사이의 통신 java.lang.Object 클래스에서는 스레드 사이의 통신을 위해 3개의 메소드를 제공
wait() 메소드 : 스레드 수행중 이 메소드를 만나면 가지고 있는 lock을 양보하고 대기상태로 들어간다 void wait() throws InterruptedException => notify() void wait(long msec) throws InterruptedException void wait(long msec, int nsec) throws InterruptedExceptionvoid msec와 nsec는 대기 시간을 의미

20 스레드 사이의 통신 notify() : 대기 상태의 스레드중에서 하나의 스레드를 깨운다
notifyAll() : 대기 상태의 모든 스레드를 깨운다 void notify() void notifyAll() Synchronized 메소드내에서 일반적으로 사용됨 그러나 문장이 호출된 시점에서 현재의 스레드가 lock을 가지고 있으므로 synchronized()메소드를 벗어나는 시점에서 사용

21 예제) 생산자/소비자 빵집아저씨 손님 바게트 빵집

22 예제1) 생산자/소비자의 관계 구현 class Producer extends Thread {
private Buffer blank; private int number = 10; public Producer(Buffer blank, int number){ this.blank = blank; this.number = number; } public void run(){ for (int j=0; j<10;j++){ blank.put(j); System.out.println(“생산자 : 생산 “+j); try{ sleep((int)(Math.random()*100)); catch(InterruptedException e){ System.out.println(e); class Consumer extends Thread { private Buffer blank; private int number; public Consumer(Buffer c, int number){ blank = c; this.number = number; } public void run(){ int val = 0; for (int j=0; j<10;j++){ val = blank.get(j); System.out.println(“소비자 : 소비 “+val);

23 class Buffer { private int contents; private boolean available = false; public synchronized int get(){ while (available == false){ try{ wait(); } catch(InterruptedException e){} available = false; notifyAll(); return contents; public synchronized int put(int value){ while (available == true){ contents = value; available = true; public class ProducerConsumer { public static void main(String args[]){ Buffer c = new Buffer(); Producer p1 = new Producer(c,1); Consumer c1 = new Consumer(c,1); p1.start(); c1.start(); }


Download ppt "10장 다중 스레드 10.1 스레드 개요 10.2 Thread 클래스 10.3 스레드 생성"

Similar presentations


Ads by Google