JAVA THREAD 2002 2 27 JAVA THREAD n

  • Slides: 31
Download presentation
JAVA THREAD 서민구 2002. 2. 27

JAVA THREAD 서민구 2002. 2. 27

JAVA THREAD n 언어자체에서 Thread 지원 (java. lang 패키지) n Runnable, Thread. Group n

JAVA THREAD n 언어자체에서 Thread 지원 (java. lang 패키지) n Runnable, Thread. Group n synchronized

Basic API n n n n n start() : 실행 stop() : 정지 –

Basic API n n n n n start() : 실행 stop() : 정지 – throw Thread. Death suspend() : 유보 resume() : 유보된 thread 재시작 interrupt() : thread 방해 is. Alive() : 실행중? set. Name() : 이름 지정 static current. Thread() : 현재 실행중인 thread join(), join(milliseconds) : 쓰레드 실행이 종료될 때까지 기다림

public class Thread. Test extends Thread { public static void main(String[] args) { for

public class Thread. Test extends Thread { public static void main(String[] args) { for ( int i. Loop. Counter = 0 ; i. Loop. Counter < 400 ; i. Loop. Counter++ ) { Thread t = new Thread. Test(); t. start(); } } public void run() { try { Thread. sleep( (int) Math. random() * 100 ); } catch (Interrupted. Exception ex) { } while ( true ) { System. out. println( get. Name() ); } } }

Thread 라이프 사이클 born Sleep expire start Notify/notify all ready 프로세서 할당 정량만료 Yield인터럽트

Thread 라이프 사이클 born Sleep expire start Notify/notify all ready 프로세서 할당 정량만료 Yield인터럽트 Issue I/O Suspend() running wait sleep waiting sleeping I/O완료 Resume() Run종료 Stop() dead blocked

thread 스케쥴링 10 A B YIELD, SLEEP, WAIT, I/O블럭킹, SUSPEND 기본시간(QUANTUM) 초과시 – 지원여부

thread 스케쥴링 10 A B YIELD, SLEEP, WAIT, I/O블럭킹, SUSPEND 기본시간(QUANTUM) 초과시 – 지원여부 보장 X 9 SLEEP, A·B 완료, WAIT, I/O블럭킹, SUSPEND 8 7 6 5 4 3 2 1 C PRIORITY

Deprecated API in Thread n Stop 하기 #1 private volatile Thread blinker; public void

Deprecated API in Thread n Stop 하기 #1 private volatile Thread blinker; public void stop() { blinker = null; } public void run() { Thread this. Thread = Thread. current. Thread(); while (blinker == this. Thread) { try { this. Thread. sleep(interval); } catch (Interrupted. Exception e) { } repaint(); } }

Deprecated API in Thread n Stop 하기 #2 public void stop() { interrupt(); }

Deprecated API in Thread n Stop 하기 #2 public void stop() { interrupt(); } public void run() { try { while ( !interrupted() ) { …… } catch (Interrupted. Exception ie) {} }

Deprecated API in Thread n Interrupt ¨ 결과 n WAIT, JOIN, SLEEP, INTERRUPTIBLE CHANNEL,

Deprecated API in Thread n Interrupt ¨ 결과 n WAIT, JOIN, SLEEP, INTERRUPTIBLE CHANNEL, SELECTOR대기중 Interrupted. Exception ¨ n 그외 ¨ ¨ ¨ 소켓 interrupted status is set Thread. interrupted()로 판단 작업에서 블럭된 상태라면 소켓을 닫는다.

Deprecated API in Thread n suspend / resume ¨ suspend() 메소드는 자신이 잡고 있는

Deprecated API in Thread n suspend / resume ¨ suspend() 메소드는 자신이 잡고 있는 락을 풀지 않 고 쓰레드를 정지시킴 A B 락 획득 Suspend() 락 획득 시도 DEADLOCK Resume()

Deprecated API in Thread n suspend / resume 하기 public void run() { while

Deprecated API in Thread n suspend / resume 하기 public void run() { while (true) { try { Thread. current. Thread(). sleep(interval); if (thread. Suspended) { synchronized(this) { while (thread. Suspended) wait(); } } } catch (Interrupted. Exception e) { } repaint(); } }

Deprecated API in Thread n suspend / resume 하기 public synchronized void mouse. Pressed(Mouse.

Deprecated API in Thread n suspend / resume 하기 public synchronized void mouse. Pressed(Mouse. Event e) { e. consume(); thread. Suspended = !thread. Suspended; if (!thread. Suspended) notify(); } ¨ synchronize 를 빼려면 thread. Suspended를 volatile 로 선언

LOCK n Atomic operations ¨ JVM은 32비트 또는 그 이하의 작업은 atomic ¨ atomic

LOCK n Atomic operations ¨ JVM은 32비트 또는 그 이하의 작업은 atomic ¨ atomic operations 이란 의미가 thread-safe operations이란 뜻은 아니다.

LOCK n Atomic operations ¨ thread safe?

LOCK n Atomic operations ¨ thread safe?

class Real. Time. Clock { private int clk. ID; private long clock. Time; public

class Real. Time. Clock { private int clk. ID; private long clock. Time; public int clock. ID() { return clk. ID; } public void set. Clock. ID(int id) { clk. ID = id; } public long time() { return clock. Time; } public void set. Time(long t) { clock. Time = t; } //. . . }

LOCK n Atomic operations ¨ NO n JAVA는 쓰레드 실행의 효율성을 위해 공유 변수의

LOCK n Atomic operations ¨ NO n JAVA는 쓰레드 실행의 효율성을 위해 공유 변수의 local copy를 만든다. ¨ 예외상황 § thread 1 : set. Clock. ID(5); § thread 2 : set. Clock. ID(10); § thread 1 : clock. ID(5) -> return 5!! n long은 64 bit. ¨ 32 bit operation 2개로 취급됨.

LOCK n SPIN LOCK ¨ 예제 : dequeue public synchronized Object dequeue() { try

LOCK n SPIN LOCK ¨ 예제 : dequeue public synchronized Object dequeue() { try { while ( head == tail ) this. wait(); } catch(Interrupted. Exception ie) { return null; } ……………… }

SWING, AWT and Thread n AWT ¨ n 대부분의 클래스가 thread-safe SWING은 thread-safe하지 않다.

SWING, AWT and Thread n AWT ¨ n 대부분의 클래스가 thread-safe SWING은 thread-safe하지 않다. ¨ 화면에 띄우기 전까지(set. Visible, pack이전까지)는 thread-safe ¨ 다음 메소드는 thread-safe하다 n n ¨ Jcomponent : repaint(), revalidate(), invalidate() JText. Area : insert, append, replace. Range JEditor. Pane : replace. Selection, set. Text JText. Pane : replace. Selection, insert. Icon, set. Logical. Style, set. Character. Attributes(), set. Paragraph. Attribtes() 이벤트 리스너 추가, 제거는 thread-safe

SWING, AWT and Thread n Swing. Utilities ¨ invoke. Later, invoke. And. Wait n

SWING, AWT and Thread n Swing. Utilities ¨ invoke. Later, invoke. And. Wait n 이벤트큐에 임의의 액션을 추가 Event. Queue. invoke. Later(new Runnable() { public void run() { label. set. Text(percentage + “% complete”); } }); n Timer

public class Bad. Perf. Class { private static int MAX_THREADS = 30; private static

public class Bad. Perf. Class { private static int MAX_THREADS = 30; private static int count = 0; private static Object lock = new Object(); public void perform. Task(…) throws … { boolean executable = true; try { synchronized ( lock ) { if ( count >= MAX_THREADS ) executable = false; else count++; } if ( executable == false ) { < "maximum threads reached !!!"> throw or return; } perform. Task 2(…. ); } finally { synchronized( lock ) { if ( executable ) count--; } } } public void perform. Task 2(…) throws … { <original business logic> } }

And… n n n n Mutex Timer Semaphore Observer, Multicasters Singleton, Critical Section, R/W

And… n n n n Mutex Timer Semaphore Observer, Multicasters Singleton, Critical Section, R/W lock Blocking Queue Reactor, Active Object Piped. Input. Stream, Piped. Output. Stream

Reference n 자바 쓰레드 능숙하게 다루기 (인포북) n IBM Developer. Works (http: //www-106. ibm.

Reference n 자바 쓰레드 능숙하게 다루기 (인포북) n IBM Developer. Works (http: //www-106. ibm. com/developerworks) n Core JAVA 2권 n JAVA Programming Bible (정보문화사) n http: //www. javaservice. net