명품 JAVA Programming 제 13 장 스레드와 멀티태스킹.

Slides:



Advertisements
Similar presentations
3. 메소드와 변수 SCJP 자격증 프로젝트 발표자 : 최선웅. 1. 메 소 드 개 념 2. 메 소 드 양 식 3. 메 소 드 변 수 4. 메 소 드 예 제 5. 참 고 문 헌 / 자 료 목 차.
Advertisements

6 장 객체 - 지향 설계 ③. 목차 GUI 레이아웃  전화기 키 패드 전화기 키 패드 전화기 키 패드 모양의 GUI 를 만드는 Telephone.java, TelephonePanel.java 를 완성해 보자.  주석을 참고하여 TelephonePanel.java.
10. 예외 처리.
11장 스레드.
클래스 class, 객체 object 생성자 constructor 접근 access 제어 이벤트 event 처리.
인공지능실험실 석사 2학기 이희재 TCP/IP Socket Programming… 제 11장 프로세스간 통신 인공지능실험실 석사 2학기 이희재
최윤정 Java 프로그래밍 클래스 상속 최윤정
명품 JAVA Programming 제 13 장 스레드와 멀티태스킹.
명품 JAVA Essential.
제8장 쓰레드 프로그래밍.
Java로 배우는 디자인패턴 입문 Chapter 5. Singleton 단 하나의 인스턴스
어서와 Java는 처음이지! 제16장 스레드.
Chapter 4 Multi-Threaded Socket
Java 10장. 다중 스레드 public class SumTest {
[ 단원 08 ] 예외처리와 스레드.
8.1 인터페이스 개요와 인터페이스 정의 8.2 인터페이스의 사용 8.3 인터페이스의 상속 8.4 인터페이스 참조
Lesson 9. 예외처리.
5장. 참조 타입.
최용술 장 Thread 최용술
명품 JAVA Essential.
10장 다중 스레드 10.1 스레드 개요 10.2 Thread 클래스 10.3 스레드 생성
명품 JAVA Programming 제 15 장 애플릿과 멀티미디어.
스레드란? 멀티 태스킹(muli-tasking)는 여러 개의 애플리케이션을 동시에 실행하여서 컴퓨터 시스템의 성능을 높이기 위한 기법 그림23-1. 병철 처리의 예.
Chap08 다중 스레드 8.1 스레드 개요 8.2 Thread 클래스와 스레드 생명주기 8.3 스레드 생성과 사용
Chapter 06 프로세스와 예약작업 관리 Solaris 1. 프로세스 관리
11장. 포인터 01_ 포인터의 기본 02_ 포인터와 Const.
SqlParameter 클래스 선문 비트 18기 발표자 : 박성한.
패키지와 접근 제어 패키지에 대하여 접근 제어에 대하여.
Lesson 7. 클래스와 메소드 - 1.
자바네트워크 제2주 실습 네트워크기초, 스레드.
Chapter 03 : 서블릿 ( Servlet ) 개요. chapter 03 : 서블릿 ( Servlet ) 개요.
10장. 예외처리.
Subject : Thread Written by: 김형근,류명운.
13. 연산자 오버로딩.
7장 인터페이스와 추상 클래스.
Java 9장. 인터페이스와 예외처리 public class SumTest {
Method & library.
사용자 함수 사용하기 함수 함수 정의 프로그램에서 특정한 기능을 수행하도록 만든 하나의 단위 작업
어서와 C언어는 처음이지 제14장.
자바응용.
Subject : Thread Written by: 김형근,류명운.
29강 JAVA 스레드 - 스레드란? - 멀티스레드 문법 - synchronized Lecturer Kim Myoung-Ho
Chap10 다중 스레드 Section 1 : 스레드 개요 Section 2 : Thread 클래스와 스레드 생명주기
HTTP 프로토콜의 요청과 응답 동작을 이해한다. 서블릿 및 JSP 를 알아보고 역할을 이해한다.
DK-128 FND 실습 아이티즌 기술연구소
Lesson 2. 기본 데이터형.
Chapter6 : JVM과 메모리 6.1 JVM의 구조와 메모리 모델 6.2 프로그램 실행과 메모리 6.3 객체생성과 메모리
자바 5.0 프로그래밍.
System.Threading Process / Thread SD50 – C# & .NET Platform.
Part 4 클래스 라이브러리 Chapter 10 : 다중 스레드 Chapter 11 : 패키지와 주요 클래스
클라우드 서버로 부터 값 읽어오기 WiFi 시리얼 보드 활용가이드 김영준 헬로앱스 (
Lab 8 Guide: 멀티스레딩 예제 2 * Critical Section을 이용한 멀티스레딩 동기화 (교재 15장, 쪽)
자바 5.0 프로그래밍.
JA A V W. 06.
Fucntion 요약.
CHAP 21. 전화, SMS, 주소록.
( Windows Service Application Debugging )
Chapter 17. 스레드.
클래스 : 기능 CHAPTER 7 Section 1 생성자(Constructor)
안드로이드 앱 개발과정 Step1. 기초과정 강사 : 정 훈 희.
JSP Programming with a Workbook
발표자 : 이지연 Programming Systems Lab.
9 브라우저 객체 모델.
Android -Data Base 윤수진 GyeongSang Univ. IT 1.
2.가상머신의 탐험 도구, Oolong에 대하여 ps lab 김윤경.
엔코더 프로그램 설명 // 쓰레드를 사용하기 때문에 변수와 핸들을 전역변수로 지정 HANDLE hDevice;
제8장 쓰레드 프로그래밍.
Power Java 제23장 스레드.
7 생성자 함수.
6 객체.
Presentation transcript:

명품 JAVA Programming 제 13 장 스레드와 멀티태스킹

멀티태스킹(multi-tasking) 개념 하나의 응용프로그램이 여러 개의 작업(태스크)을 동시에 처리 다림질하면서 이어폰으로 전화하는 주부 운전하면서 화장하는 운전자 제품의 판독과 포장 작업의 두 기능을 갖춘 기계

스레드(thread) 개념과 실(thread) 가지고 바느질하는 것과 자바의 스레드는 일맥 상통함 스레드 A 생성 스레드 A 스레드 B 생성 스레드 B

스레드와 멀티스레딩 스레드 자바의 멀티태스킹 프로그램 코드를 이동하면서 실행하는 하나의 제어 멀티스레딩만 가능 프로세스 개념은 자바에 존재하지 않고, 스레드의 개념만 존재 스레드는 실행 단위 스레드는 스케쥴링 단위 하나의 응용프로그램을 여러 개의 스레드로 구성 가능 스레드 사이의 통신에 따른 오버헤드가 크지 않음

웹 서버의 멀티스레딩 사례 웹 서버 웹 서버 시스템 웹 서비스 스레드 웹 서비스 스레드 웹 서비스 스레드 웹 서비스 스레드 웹문서 요청 웹 클라이언트 웹 서비스 스레드 웹문서 전송 각 클라이언트 당 웹 서비스 스레드 생성 웹문서 요청 웹 서비스 스레드 웹 클라이언트 웹문서 전송 웹 서버 웹 서비스 스레드 웹문서 요청 웹문서 전송 웹 클라이언트 웹 서비스 스레드 웹문서 요청 웹문서 전송 웹 클라이언트 웹 서버 시스템

자바 스레드(Thread)란? 자바 스레드 JVM은 하나의 자바 응용프로그램만을 실행 하나의 응용프로그램은 하나 이상의 스레드로 구성 가능

JVM과 자바 응용프로그램, 스레드의 관계 JVM JVM JVM 운영체제 운영체제 운영체제 하드웨어 하드웨어 하드웨어 자바 응용 프로그램 자바 응용 프로그램 자바 응용 프로그램1 자바 응용 프로그램2 자바 응용 프로그램3 자바 스레드 자바 스레드 자바 스레드 JVM JVM JVM 운영체제 운영체제 운영체제 하드웨어 하드웨어 하드웨어 JVM은 오직 하나의 자바 응용프로그램만 실행 JVM은 여러 개의 자바 응용프로그램 실행 불가 하나의 응용프로그램은 여러 개의 스레드 가질 수 있음 자바 응용 프로그램 1 통신 자바 응용 프로그램 2 JVM JVM 운영체제 하드웨어 두 개의 자바 응용프로그램이 동시에 실행시키고자 하면 두 개의 JVM을 이용하고 응용프로그램은 서로 소켓 등을 이용하여 통신

자바 스레드와 JVM 자바응용프로그램 각 스레드의 스레드 코드는 응용프로그램 내에 존재함 JVM이 스레드를 관리함 객체 객체 객체 객체 각 스레드의 스레드 코드는 응용프로그램 내에 존재함 스레드 코드 1 스레드 코드 2 스레드 코드 3 스레드 코드 4 스레드 정보1 스레드 정보2 스레드 정보3 스레드 정보4 JVM이 스레드를 관리함 스레드가 몇 개인지? 스레드 코드의 위치가 어디인지? 스레드의 우선순의는 얼마인지? 등 JVM 운영체제(Windows or Linux) 하드웨어(PC or Embedded Board, 워크스테이션 등) 현재 하나의 JVM에 의해 4 개의 스레드가 실행 중이며 그 중 스레드 2가 JVM에 의해 스케쥴링되어 실행되고 있음

스레드 만들기 스레드 실행을 위해 개발자에 의해 이루어지는 작업 자바에서 스레드 만드는 2 가지 방법 스레드 코드 작성 JVM에게 스레드를 생성하고 스레드 코드를 실행하도록 요청 자바에서 스레드 만드는 2 가지 방법 java.lang.Thread 클래스를 이용하는 경우 java.lang.Runnable 인터페이스를 이용하는 경우

Thread 클래스의 메소드 명품 JAVA Programming 생성자 다른 스레드가 죽을 때까지 기다리기 Thread(Runnable target) Thread(String name) Thread(Runnable target, String name) 스레드 시작시키기 void start() 스레드 코드 void run() 스레드 잠자기 static void sleep(long mills) 다른 스레드 죽이기 void interrupt() 다른 스레드에게 양보 static void yield() 현재 스레드의 실행을 중단하고 다른 스 레드가 실행될 수 있도록 양보한다. 다른 스레드가 죽을 때까지 기다리기 void join() 현재 스레드 객체 알아내기 static Thread currentThread() 스레드 ID 알아내기 long getId() 스레드 이름 알아내기 String getName() 스레드 우선순위값 알아내기 int getPriority() 스레드의 상태 알아내기 Thread.State getState() 명품 JAVA Programming

Thread 클래스를 이용한 스레드 생성 스레드 클래스 작성 스레드 코드 작성 스레드 객체 생성 스레드 시작 run() 메소드 오버라이딩 run() 메소드를 스레드 코드라고 부름 run() 메소드에서 스레드 실행 시작 스레드 객체 생성 스레드 시작 start() 메소드 호출 public TimerThread extends Thread { .................................................... public void run() { // run() 오버라이딩 ......................... } TimerThread th = new TimerThread(); th.start();

* Thread를 상속받아 1초 단위로 초 시간을 출력하는 TimerThread 스레드 작성 스레드 클래스 정의 class TimerThread extends Thread { int n = 0; public void run() { while(true) {//무한루프를 실행한다. System.out.println(n); n++; try { sleep(1000); //1초동안 잠을 잔 후 깨어난다. } catch(InterruptedException e){return;} * Thread를 상속받아 1초 단위로 초 시간을 출력하는 TimerThread 스레드 작성 스레드 코드 작성 1초에 한 번씩 n을 증가시켜 콘솔에 출력한다. 실행 결과 public class TestThread { public static void main(String [] args) { TimerThread th = new TimerThread(); th.start(); } 1 2 3 4 스레드 객체 생성 스레드 시작 main() 스레드 TimerThread 스레드 run() { ............. } th main 스레드의 스레드 정보 TimerThread 의 스레드 정보 JVM

예제 13-1 : Thread를 상속받아 1초 단위의 타이머 만들기 import java.awt.*; import javax.swing.*; class TimerThread extends Thread { JLabel timerLabel; public TimerThread(JLabel timerLabel) { this.timerLabel = timerLabel; } public void run() { int n=0; while(true) { timerLabel.setText(Integer.toString(n)); n++; try { Thread.sleep(1000); catch(InterruptedException e) { return; public class ThreadTimerEx extends JFrame { public ThreadTimerEx() { setTitle(“ThreadTimerEx 예제”); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(new FlowLayout()); JLabel timerLabel = new JLabel(); timerLabel.setFont(new Font(“Gothic“, Font.ITALIC, 80)); TimerThread th = new TimerThread(timerLabel); c.add(timerLabel); setSize(300,150); setVisible(true); th.start(); } public static void main(String[] args) { new ThreadTimerEx();

스레드 주의 사항 run() 메소드가 종료하면 스레드는 종료한다. 한번 종료한 스레드는 다시 시작시킬 수 없다. run()메소드의 종료는 run()메소드가 종료하거나 return하는 경우 스레드가 무한이 존재하게 하려면 run() 메소드 내에 무한 루프 가 실행되어야 한다. 한번 종료한 스레드는 다시 시작시킬 수 없다. 스레드 객체를 생성하여 다시 스레드로 등록하여야 한다. 한 스레드에서 다른 스레드를 강제 종료할 수 있다. 뒤에서 다룸

Runnable 인터페이스로 스레드 만들기 스레드 클래스 작성 Runnable 인터페이스 구현하는 새 클래스 작성 스레드 코드 작성 run() 메소드 오버라이딩 run() 메소드를 스레드 코드라고 부름 run() 메소드에서 스레드 실행 시작 스레드 객체 생성 스레드 시작 start() 메소드 호출 class TimerRunnable implements Runnable { ................................................................ public void run() { // run() 메소드 오버라이딩 ......................... } Thread th = new Thread(new TimerRunnable()); th.start();

*Runnable 인터페이스를 상속받아 1초 단위로 초 시간을 출력하는 스레드 작성 클래스로 구현 class TimerRunnable implements Runnable { int n = 0; public void run() { while(true) {//무한루프를 실행한다. System.out.println(n); n++; try { Thread.sleep(1000); //1초동안 잠을 잔 후 깨어난다. } catch(InterruptedException e){return;} *Runnable 인터페이스를 상속받아 1초 단위로 초 시간을 출력하는 스레드 작성 스레드 코드 작성 1초에 한 번씩 n을 증가시켜 콘솔에 출력한다. 실행 결과 1 2 3 4 public class TestRunnable { public static void main(String [] args) { Thread th = new Thread(new TimerRunnable()); th.start(); } 스레드 객체 생성 스레드 시작 main() 스레드 Thread 스레드 run() { ............. } th main 스레드의 스레드 정보 Thread 의 스레드 정보 JVM

예제 13-2 : Runnable인터페이스를 구현하여 1초 단위 타이머 만들기 public class RunnableTimerEx extends JFrame { public RunnableTimerEx() { setTitle(“RunnableTimerEx 예제”); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(new FlowLayout()); JLabel timerLabel = new JLabel(); timerLabel.setFont(new Font(“Gothic“, Font.ITALIC, 80)); TimerRunnable runnable = new TimerRunnable(timerLabel); Thread th = new Thread(runnable); c.add(timerLabel); setSize(300,150); setVisible(true); th.start(); } public static void main(String[] args) { new RunnableTimerEx(); import java.awt.*; import javax.swing.*; class TimerRunnable implements Runnable { JLabel timerLabel; public TimerRunnable(JLabel timerLabel) { this.timerLabel = timerLabel; } public void run() { int n=0; while(true) { timerLabel.setText(Integer.toString(n)); n++; try { Thread.sleep(1000); catch(InterruptedException e) { return;

예제 13-3 : 깜박이는 레이블 만들기 import java.awt.*; import javax.swing.*; class FlickeringLabel extends JLabel implements Runnable{ public FlickeringLabel(String text) { super(text); // JLabel 생성자 호출 setOpaque(true); // 배경색 변경이 가능하도록 설정 Thread th = new Thread(this); th.start(); } public void run() { int n=0; while(true) { if(n == 0) setBackground(Color.YELLOW); else setBackground(Color.GREEN); if(n == 0) n = 1; else n = 0; try { Thread.sleep(500); // 0.5초 동안 잠을 잔다. catch(InterruptedException e) { return; public class FlickeringLabelEx extends JFrame { public FlickeringLabelEx() { setTitle(“FlickeringLabelEx 예제”); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(new FlowLayout()); // 깜박이는 레이블 생성 FlickeringLabel fLabel = new FlickeringLabel(“깜박”); // 깜박이지 않는 레이블 생성 JLabel label = new JLabel(“안깜박“); FlickeringLabel fLabel2 = new FlickeringLabel(“여기도 깜박”); c.add(fLabel); c.add(label); c.add(fLabel2); setSize(300,150); setVisible(true); } public static void main(String[] args) { new FlickeringLabelEx();

예제 실행 : 깜박이는 레이블 만들기

스레드 정보 필드 타입 내용 스레드 이름 스트링 스레드의 이름으로서 사용자가 지정 스레드 ID 정수 스레드 고유의 식별자 번호 스레드의 PC(Program Count) 현재 실행 중인 스레드 코드의 주소 스레드 상태 NEW, RUNNABLE, WAITING, TIMED_WAITING, BLOCK, TERMINATED 등 6개 상태 중 하나 스레드 우선순위 스레드 스케줄링 시 사용되는 우선순위 값으로서 1~10 사이의 값이며 10이 최상위 우선순위 스레드 그룹 여러 개의 자바 스레드가 하나의 그룹을 형성할 수 있으며 이 경우 스레드가 속한 그룹 스레드 레지스터 스택 메모리 블록 스레드가 실행되는 동안 레지스터들의 값

스레드 상태 스레드 상태 6 가지 스레드 상태는 JVM에 의해 TCB 기록 관리됨 NEW RUNNABLE WAITING 스레드가 생성되었지만 스레드가 아직 실행할 준비가 되지 않았음 RUNNABLE 스레드가 JVM에 의해 실행되고 있거나 실행 준비되어 스케쥴링을 기다 리는 상태 WAITING 어떤 Object 객체에서 다른 스레드가 notify(), notifyAll()을 불러주기를 기다리고 있는 상태. 스레드 동기화를 위해 사용 TIMED_WAITING 스레드가 sleep(n) 호출로 인해 n 밀리초 동안 잠을 자고 있는 상태 BLOCK 스레드가 I/O 작업을 요청하면 JVM이 자동으로 이 스레드를 BLOCK 상 태로 만든다. TERMINATED 스레드가 종료한 상태 스레드 상태는 JVM에 의해 TCB 기록 관리됨

스레드 상태와 생명 주기 threadA = new Thread() threadB 스레드 상태 6 가지 NEW RUNNABLE WAITING TIMED_WAITING BLOCK TERMINATED start() I/O작업 완료 타임아웃 RUNNABLE (준비) yield() run() 또는 JVM에 의해 스케쥴링될 때 RUNNABLE (running, 실행중) Object.wait() I/O작업 요청 WAITING(대기) 스레드 종료 BLOCK(봉쇄) sleep() threadB TIMED_WAITING (시간 대기) TERMINATED (종료) Object.notify(); Object.notifyAll(); ** wait(), notify(), notifyAll()은 Thread의 메소드가 아니며 Object의 메소드임

스레드 우선 순위와 스케쥴링 스레드의 우선 순위 스레드 우선 순위는 응용프로그램에서 변경 가능 최대값 = 10(MAX_PRIORITY) 최소값 = 1(MIN_PRIORITY) 보통값 = 5(NORMAL_PRIORITY) 스레드 우선 순위는 응용프로그램에서 변경 가능 void setPriority(int priority) int getPriority() main() 스레드의 우선 순위 값은 초기에 5 스레드 생성 시 부모 스레드와 동일한 우선순위값으로 탄생 JVM의 스케쥴링 정책 철저한 우선 순위 기반 가장 높은 우선 순위의 스레드가 우선적으로 스케쥴링 동일한 우선 순위의 스레드는 돌아가면서 스케쥴링(라운드 로빈 ).

main()은 자바의 main 스레드 main() 메소드 JVM에 의해 자동으로 스레드화 자바 스레드 : main 스레드 public class ThreadMainEx { public static void main(String [] args) { long id = Thread.currentThread().getId(); String name = Thread.currentThread().getName(); int priority = Thread.currentThread().getPriority(); Thread.State s = Thread.currentThread().getState(); System.out.println("현재 스레드 이름 = " + name); System.out.println("현재 스레드 ID = " + id); System.out.println("현재 스레드 우선순위 값 = " + priority); System.out.println("현재 스레드 상태 = " + s); } 실행 결과 콘솔 화면 현재 스레드 이름 = main 현재 스레드 ID = 1 현재 스레드 우선순위 값 = 5 현재 스레드 상태 = RUNNABLE

catch(InterruptedException e) 스레드 종료와 타 스레드 강제 종료 class TimerThread extends Thread { int n = 0; public void run() { while(true) { System.out.println(n); // 화면에 카운트 값 출력 n++; try { sleep(1000); } catch(InterruptedException e){ return; // 에외를 받고 스스로 리턴하여 종료 스레드 스스로 종료 run() 메소드의 리턴 타 스레드 강제 종료 interrupt() 메소드 사용 public static void main(String [] args) { TimerThread th = new TimerThread(); th.start(); th.interrupt(); // TimerThread 강제 종료 } 만일 return 하지 않으면 스레드는 종료하지 않음 TimerThread 스레드 main() 스레드 catch(InterruptedException e) {return;} th th.interrupt(); InterruptedException 발생

예제 13-4 : 타이머 스레드 강제 종료 public class ThreadInterruptEx extends JFrame { Thread th; public ThreadInterruptEx() { setTitle(“ThreadInterruptEx 예제“); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(new FlowLayout()); JLabel timerLabel = new JLabel(); timerLabel.setFont(new Font(“Gothic“, Font.ITALIC, 80)); TimerRunnable runnable = new TimerRunnable(timerLabel); th = new Thread(runnable); // 스레드 생성 c.add(timerLabel); // 버튼을 생성하고 Action 리스너 등록 JButton btn =new JButton(“kill Timer“); btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { th.interrupt(); // 타이머 스레드 강제 종료 JButton btn = (JButton)e.getSource(); btn.setEnabled(false); // 버튼 비활성화 } }); c.add(btn); setSize(300,150); setVisible(true); th.start(); // 스레드 동작시킴 public static void main(String[] args) { new ThreadInterruptEx(); import java.awt.*; import java.awt.event.*; import javax.swing.*; class TimerRunnable implements Runnable { JLabel timerLabel; public TimerRunnable(JLabel timerLabel) { this.timerLabel = timerLabel; } public void run() { int n=0; while(true) { timerLabel.setText(Integer.toString(n)); n++; try { Thread.sleep(1000); // 1초 동안 잠을 잔다. catch(InterruptedException e) { return; // 예외가 발생하면 스레드 종료

예제 실행 : 1초씩 작동하는 타이머 스레드 강제 종료 타이머는 정상 작동한다. Kill Timer 버튼을 클릭하면 타이머가 멈춘다. 버튼은 비활성화된다.

스레드 동기화(Thread Synchronization) 멀티스레드 프로그램의 주의점 다수의 스레드가 공유 데이타에 동시에 접근하는 경우 공유데이타의 값에 예상치 못한 결과 발생 가능 스레드 동기화 멀티스레드의 공유 데이타의 동시 접근 문제 해결책 공유데이타를 접근하고하 하는 모든 스레드의 한 줄 세우기 한 스레드가 공유 데이타에 대한 작업을 끝낼 때까지 다른 스레 드가 공유 데이타에 접근하지 못하도록 함

두 스레드가 프린터에 동시 쓰기를 수행하는 경우 스레드 B “자바는 좋은 것이야. 배워서 많이 알고 취직도 잘 되고.” 스레드 A 스레드 B 스레드 A가 프린터 사용을 끝낼때까지 기다린다. 스레드 A “자바는 좋은 것이야. 배워서 많이 알고 취직도 잘 되고.” “I love you forever.” “I love you forever.” I love you forever. I love 자바는 좋은 것이야. you 배워서 많이 forever. 알고 취직도 잘 되고. 두 개의 스레드가 동시에 프린터에 쓰는 경우 문제 발생 두 개의 스레드가 순서를 지켜 프린터에 쓰는 경우 정상 출력

공유 집계판을 동시 접근하는 경우 두 학생이 동시에 방에 들어와서 집계판을 수정하는 경우 학생 B는 학생 A가 계수를 끝낸 후 계수를 시작함 학생 A는 60을 기록하고 나감 50+10=60 50+10=60 학생 A 학생 C 학생 B 학생 A 학생 B 두 학생이 동시에 방에 들어와서 집계판을 수정하는 경우 집계판의 결과가 잘못됨 방에 먼저 들어간 학생이 집계를 끝내기를 기다리는 경우 정상 처리

synchronized 키워드 synchronized 키워드 synchronized 키워드 사용 가능한 부분 한 스레드만이 독점적으로 실행되어야 하는 부분(동기화 코드)을 표시하는 키워드 임계 영역(ciritical section)을 표기하는 키워드 synchronized 키워드 사용 가능한 부분 메소드 전체 코드 블럭 synchronized 부분의 실행 모니터를 소유 모니터란 해당 객체를 독점적으로 사용할 수 있는 권한 모니터를 먼저 소유한 스레드가 모니터를 내놓을 때까지 다른 스레드는 기다려야 한다. synchronized void add() { int n = getCurrentSum(); n+=10; setCurrentSum(n); } void execute() { // 다른 코드들 // synchronized(this) { synchoronized 메소드 synchoronized 코드블럭

synchronized 사용 예 : 집계판 사례를 코딩 public class SynchronizedEx { public static void main(String [] args) { SyncObject obj = new SyncObject(); Thread th1 = new WorkerThread("kitae", obj); Thread th2 = new WorkerThread("hyosoo", obj); th1.start(); th2.start(); } class SyncObject { int sum = 0; synchronized void add() { int n = sum; Thread.currentThread().yield(); n += 10; sum = n; System.out.println(Thread.currntThread().getName() + " : " + sum); int getSum() {return sum;} class WorkerThread extends Thread { SyncObject sObj; WorkerThread(String name, SyncObject sObj) { super(name); this.sObj = sObj; public void run() { int i=0; while(i<10) { sObj.add(); i++; 집계판 : class SyncObject 각 학생 : class WorkerThread kitae : 10 hyosoo : 20 kitae : 30 hyosoo : 40 kitae : 50 hyosoo : 60 kitae : 70 hyosoo : 80 hyosoo : 90 hyosoo : 100 hyosoo : 110 hyosoo : 120 hyosoo : 130 hyosoo : 140 kitae : 150 kitae : 160 kitae : 170 kitae : 180 kitae : 190 kitae : 200 kitae와 hyosoo가 각각 10번씩 add()를 호출하였으며 동기화가 잘 이루어져서 최종 누적 점수 sum이 200이 됨

SyncObject 객체에 대한 스레드의 동시 접근 sObj = new SyncObject(); synchronized void add() { int n = sum; Thread.currentThread().yield(); n += 10; sum = n; System.out.println(Thread.currntThread(). getName() + " : " + sum); } add() 대기 중 add() 실행 중 WorkerThread WorkerThread SyncObject sObj; public void run() { int i=0; while(i<10) { sObj.add(); i++; } SyncObject sObj; public void run() { int i=0; while(i<10) { sObj.add(); i++; } th1 스레드 th2 스레드

집계판 예에서 synchronized 사용하지 않을 경우 public class SynchronizedEx { public static void main(String [] args) { SyncObject obj = new SyncObject(); Thread th1 = new WorkerThread("kitae", obj); Thread th2 = new WorkerThread("hyosoo", obj); th1.start(); th2.start(); } class SyncObject { int sum = 0; synchronized void add() { int n = sum; Thread.currentThread().yield(); n += 10; sum = n; System.out.println(Thread.currntThread().getName() + " : " + sum); int getSum() {return sum;} class WorkerThread extends Thread { SyncObject sObj; WorkerThread(String name, SyncObject sObj) { super(name); this.sObj = sObj; public void run() { int i=0; while(i<10) { sObj.add(); i++; kitae : 10 hyosoo : 20 kitae : 30 hyosoo : 30 kitae : 40 hyosoo : 50 kitae : 50 kitae : 60 hyosoo : 60 kitae : 70 hyosoo : 70 kitae : 80 hyosoo : 90 kitae : 100 hyosoo : 100 kitae : 110 hyosoo : 120 kitae : 130 hyosoo : 140 hyosoo : 150 add() 충돌 add() 충돌 add() 충돌 add() 충돌 add() 충돌 kitae와 hyosoo가 각각 10번씩 add()를 호출하였지만 동기화가 이루어지지 않아 공유 변수 sum에 대한 접근에 충돌이 있었고 수를 많이 잃어버리게 되어 누적 점수가 150 밖에 되지 못함

wait(), notify(), notifyAll() 동기화 객체 두 개 이상의 스레드 사이에 동기화 작업에 사용되는 객체 동기화 메소드 synchonized 블럭 내에서만 사용되어야 함 wait() 다른 스레드가 notify()를 불러줄 때까지 기다린다. notify() wait()를 호출로 인해 대기중인 스레드를 깨우고 RUNNABLE 상태로 한다. 2개 이상의 스레드가 대기중이라도 오직 한 개의 스레드만 깨워 RUNNABLE 상태 로 한다. notifyAll() wait()를 호출로 인해 대기중인 모든 스레드를 깨우고 이들을 모두 RUNNABLE 상 태로 다. 동기화 메소드는 Object의 메소드이다. 모든 객체가 동기화 객체가 될 수 있다. Thread 객체도 동기화 객체로 사용될 수 있다.

            명품 JAVA Programming 하나의 Thread가 ObjectS.wait()를 호출하여 잠을 자는 경우 ObjectS  ThreadB ThreadA wait() notify() notifyAll()  ThreadA는 ObjectS.notify()를 호출하여 잠자는 ThreadB를 깨운다. data 4 개의 스레드가 모두 ObjectS.wait()를 호출하여 잠을 자며 ThreadA는 ObjectS.notifyAll()를 호출하는 경우 ThreadB  ObjectS  ThreadC 잠자는 4 개의 스레드를 모드 깨운다. ThreadA wait() notify() notifyAll()  ThreadD   ThreadE data 4 개의 스레드가 모두 ObjectS.wait()를 호출하여 잠을 자며 ThreadA는 ObjectS.notify()를 호출하는 경우 ThreadB  ObjectS  ThreadC ThreadA wait() notify() notifyAll() 잠자는 4개의 스레드 중 하나만 깨운다. 선택받지 못한 3 개의 스레드는 계속 잠을 잔다.   ThreadD  ThreadE 명품 JAVA Programming data

예제 13-5 : wait(), notify()를 이용한 타원 그리기 public void run() { try { synchronized(obj) { obj.wait(); } catch(InterruptedException e) { return; while(true) { if(p.isValid()) { if(!running) { int x = r.nextInt(p.getWidth()); int y = r.nextInt(p.getHeight()); int w = r.nextInt(100); int h = r.nextInt(100); p.setObj(x,y,w,h); p.repaint(); Thread.sleep(300); catch(InterruptedException e){return;} public static void main(String[] args) { new ThreadWaitNotifyEx(); import javax.swing.*; import java.util.*; import java.awt.*; import java.awt.event.*; public class ThreadWaitNotifyEx extends JFrame{ public ThreadWaitNotifyEx() { this.setContentPane(new DrawingPanel()); this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); this.setSize(300,300); this.setVisible(true); } class DrawingPanel extends JPanel { Object obj = new Object(); DrawingThread th = new DrawingThread(this); Rectangle r = new Rectangle(0,0,0,0); public DrawingPanel () { this.addMouseListener(new MouseHandler()); th.start(); public void setObj(int x, int y, int w, int h) { r.x = x; r.y = y; r.width = w; r.height = h; public void paintComponent(Graphics g) { if(r.width == 0 || r.height == 0) return; g.drawOval(r.x, r.y, r.width, r.height); class MouseHandler extends MouseAdapter { public void mouseEntered(MouseEvent e) { setTitle("Make Drawing to Start"); th.wakeup(); } public void mouseExited(MouseEvent e) { setTitle("Make Drawing to Pause"); th.pause(); class DrawingThread extends Thread { boolean running = true; Object obj; DrawingPanel p; Random r = new Random(new Date().getTime()); public DrawingThread(DrawingPanel p) { this.p = p; this.obj = new Object(); public void wakeup() { running = true; synchronized(obj) { obj.notify(); public void pause() { running = false;

실행 결과 마우스가 올라가 있는 동안에는 랜덤한 타원이 계속 그려진다. 마우스가 내려가면 타원 생성이 멈추고 타이틀에 start가 표시됨 마우스가 내려가면 타원 생성이 멈추고 타이틀에 pause 가 표시됨