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

Slides:



Advertisements
Similar presentations
Transaction ㅇ Transaction 을 직접 구현하려면, 까다로운 설계와 복잡한 코드를 필요로 하고 수정에 공수가 많이 들게 된다. ㅇ 스프링에서 제공하는 Transaction Manager 를 사용하여 쉽고 간편하게 어려운 트랜잭션을 해결할 수 있다. xml.
Advertisements

멘토링 2 주차 장 프로그래밍을 위한 자바의 자료형  값이 변하지 않는 상수  메모리 기억공간인 변수.
명품 JAVA Programming 제 3 장 반복문, 배열, 예외처리.
명품 JAVA Programming 제 13 장 스레드와 멀티태스킹.
11장. 프로토콜 핸들러 AI &HC I LAB 김 성 현.
6장 java.applet.Applet의 네트워크 메쏘드들
명품 JAVA Essential.
어서와 Java는 처음이지! 제2장 자바 프로그래밍 기초.
10. 예외 처리.
Ch.22 Command Pattern 장 덕 성 계명대학교 컴퓨터공학과 정보공학실험실
컴퓨터 응용 및 실습 Part1. OOP&Java Programming data type Review
9장. 스윙 프로그래밍.
GUI 이벤트, 이벤트 리스너와 이벤트 소스 그림 그리기 내부 클래스
제7장 이벤트 프로그래밍.
명품 JAVA Essential.
어서와 Java는 처음이지! 제2장 자바 프로그래밍 기초.
컴퓨터 프로그래밍 실습 #7 제 4 장 GUI 클래스 작성.
명품 JAVA Essential.
J2ME(Java 2 Micro Edition) 무선 장치용 UI의 핵심 컴포넌트
제 4장 문 장 배정문 혼합문 제어문 표준 입출력.
명품 JAVA Programming.
어서와 Java는 처음이지! 제16장 스레드.
9 표준 액션.
9장 AWT(1).
Chapter 02 자바 기본구조 자바 프로그래밍의 기초적인 문법을 소개
제7장 제어구조 I – 식과 문장.
[ 단원 08 ] 예외처리와 스레드.
명품 JAVA Essential.
Power Java 제4장 자바 프로그래밍 기초.
[INA470] Java Programming Youn-Hee Han
8장 자바 입출력.
명품 JAVA Programming 제 12 장 그래픽.
Swing 컴포넌트 텍스트 컴포넌트 텍스트 필드 텍스트 영역 스크롤 페인 체크 박스 라디오 버튼.
Choi, Namseok Java 기초 (Java의 제어문과 배열) Choi, Namseok
01. 직렬화와 역직렬화에 대하여 객체의 직렬화 직렬화와 역직렬화
5장 조건과 반복 ③.
실전 사운드 처리 프로그래밍 Lecture #11.
명품 Java Programming.
Java의 정석 제 12 장 쓰레드(thread) Java 정석 남궁성 강의
최용술 장 Thread 최용술
명품 JAVA Essential.
Chap07 예외 처리 7.1 예외의 개요 7.2 예외 관련 클래스 7.3 예외 처리.
10장 다중 스레드 10.1 스레드 개요 10.2 Thread 클래스 10.3 스레드 생성
2장 자바환경과 자바 프로그램 2.1 자바 개발 환경 2.2 자바 통합환경 2.3 자바 응용 프로그램과 애플릿 프로그램
9장 AWT(1).
명품 JAVA Programming 제 15 장 애플릿과 멀티미디어.
Chap08 다중 스레드 8.1 스레드 개요 8.2 Thread 클래스와 스레드 생명주기 8.3 스레드 생성과 사용
주소록 프로그램.
제 4주 2014년 1학기 강원대학교 컴퓨터학부 담당교수: 정충교
4장 Random Number 프로그래밍 언어 실험실 석사 3학기 박중기
Chapter6 : JVM과 메모리 6.1 JVM의 구조와 메모리 모델 6.2 프로그램 실행과 메모리 6.3 객체생성과 메모리
Subject : Thread Written by: 김형근,류명운.
03. 안드로이드를 위한 Java 문법 제목. 03. 안드로이드를 위한 Java 문법 제목.
Ch.1 Iterator Pattern <<interface>> Aggregate +iterator
Chap10 다중 스레드 Section 1 : 스레드 개요 Section 2 : Thread 클래스와 스레드 생명주기
제 2장 어휘구조와 자료형 토 큰 리 터 럴 주 석 자 료 형 배 열 형.
컴퓨터공학실습(I) 3주 인공지능연구실.
Java IT응용시스템공학과 김형진 교수 5장. 객체지향 개념 public class SumTest {
JA A V W. 04.
자바 5.0 프로그래밍.
Java 3장. 자바의 기본 구조 I : 변수, 자료형, 연산자 public class SumTest {
제8장 쓰레드 프로그래밍.
제 4 장 클래스 작성 Lab 4- 2.
Outline 클래스의 해부 캡슐화(Encapsulation) 메쏘드의 해부 그래픽 객체(Graphical Objects)
JVM의 구조와 메모리 모델 JVM의 내부 구조 클래스 파일 클래스 로더 메소드(method) 영역 힙(heap) 영역
C# 10장. 참조형.
자바 프로그래밍 Thread를 이용한 애니메이션 서울호서전문학교 게임프로그램개발과.
Java 5장. 객체지향 개념 public class SumTest {
Chapter8 : 인터페이스와 패키지 8.1 인터페이스 개요와 인터페이스 정의 8.2 인터페이스의 사용
임베디드 프로그래밍 Lecture #
Presentation transcript:

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

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

스레드(thread) 개념과 실(thread) 스레드 B 생성 스레드 B

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

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

자바 스레드(Thread)란? 자바 스레드 JVM과 멀티스레드의 관계 하나의 응용프로그램은 하나 이상의 스레드로 구성 가능

JVM과 자바 응용프로그램, 스레드의 관계 두 개의 자바 응용프로그램이 동시에 실행시키고자 하면

자바 스레드와 JVM 각 스레드의 스레드 코드는 응용프로그램 내에 존재함 JVM이 스레드를 관리함 스레드가 몇 개인지? 스레드 코드의 위치가 어디인지? 스레드의 우선순위는 얼마인지? 등 현재 하나의 JVM에 의해 4 개의 스레드가 실행 중이며 그 중 스레드 2가 JVM에 의해 스케쥴링되어 실행되고 있음

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

Thread 클래스의 메소드 생성자 다른 스레드가 죽을 때까지 기다리기 현재 스레드 객체 알아내기 스레드 시작시키기 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()

Thread 클래스를 이용한 스레드 생성 스레드 클래스 작성 스레드 코드 작성 스레드 객체 생성 스레드 시작 run() 메소드 오버라이딩 run() 메소드를 스레드 코드라고 부름 run() 메소드에서 스레드 실행 시작 스레드 객체 생성 스레드 시작 start() 메소드 호출 스레드로 작동 시작 JVM에 의해 스케쥴되기 시작함 class 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;} 스레드 코드 작성 1초에 한 번씩 n을 증가시켜 콘솔에 출력한다. 1 2 3 4 public class TestThread { public static void main(String [] args) { TimerThread th = new TimerThread(); th.start(); } 스레드 객체 생성 스레드 시작 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() 메소드가 종료하면 스레드는 종료한다. 한번 종료한 스레드는 다시 시작시킬 수 없다. 다시 스레드 객체를 생성하고 스레드로 등록하여야 한다. 한 스레드에서 다른 스레드를 강제 종료할 수 있다. 뒤에서 다룸

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; } 스레드 코드 작성 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초 단위 타이머 만들기 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; 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 imerRunnable(timerLabel); Thread th = new Thread(runnable); c.add(timerLabel); setSize(300,150); setVisible(true); th.start(); } public static void main(String[] args) { new RunnableTimerEx();

예제 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();

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

스레드 정보

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

스레드 상태와 생명 주기 스레드 상태 6 가지 NEW RUNNABLE WAITING TIMED_WAITING BLOCK TERMINATED ** 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 스레드와 main() 메소드 JVM은 응용프로그램이 실행될 때 스레드 생성 : main 스레드 main 스레드에 의해 main() 메소드 실행 main() 메소드가 종료하면 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) 스레드 종료와 타 스레드 강제 종료 스스로 종료 run() 메소드 리턴 타 스레드에서 강제 종료 : interrupt() 메소드 사용 class TimerThread extends Thread { int n = 0; public void run() { while(true) { System.out.println(n); // 화면에 카운트 값 출력 n++; try { sleep(1000); } catch(InterruptedException e){ return; // 예외를 받고 스스로 리턴하여 종료 public static void main(String [] args) { TimerThread th = new TimerThread(); th.start(); th.interrupt(); // TimerThread 강제 종료 } 만일 return 하지 않으면 스레드는 종료하지 않음 main() 스레드 TimerThread 스레드 th th.interrupt(); catch(InterruptedException e) {return;} InterruptedException 발생 main 스레드의 interrupt() 메소드 호출에 의해 catch 문 실행. 그리고 종료

예제 13-4 : 타이머 스레드 강제 종료 public class ThreadInterruptEx extends JFrame { Thread th; public ThreadInterruptEx() { setTitle(" hreadInterruptEx 예제"); 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 버튼을 클릭하면 타이머가 멈춘다. 버튼은 비활성화된다.

flag를 이용한 종료 스레드 A가 스레드 B의 flag 를 true로 만들면, 스레드 B 가 스스로 종료하는 방식 class TimerThread extends Thread { int n = 0; bool flag = false; // false로 초기화 public void finish() { flag = true; } public void run() { while(true) { System.out.println(n); // 화면에 카운트 값 출력 n++; try { sleep(1000); if(flag == true) return; // 스레드 종료 } catch(InterruptedException e){ return; 스레드 A가 스레드 B의 flag 를 true로 만들면, 스레드 B 가 스스로 종료하는 방식 public static void main(String [] args) { TimerThread th = new TimerThread(); th.start(); th.finish(); // TimerThread 강제 종료 } TimerThread 스레드 main() 스레드 true th th.finish(); flag false if(flag == true) return; // 스레드 종료 flag 멤버를 true로 변경

예제 13-5 flag를 이용한 스레드 강제 종료 import java.awt.*; import java.awt.event.*; import javax.swing.*; class RandomThread extends Thread { Container contentPane; boolean flag=false; // 스레드의 종료 명령을 표시하는 플래그. // true : 종료 지시 public RandomThread(Container contentPane) { this.contentPane = contentPane; } void finish() { // 스레드 종료 명령을 flag에 표시 flag = true; public void run() { while(true) { int x = ((int)(Math.random()*contentPane.getWidth())); int y = ((int)(Math.random()*contentPane.getHeight())); JLabel label = new JLabel("Java"); //새 레이블 생성 label.setSize(80, 30); label.setLocation(x, y); contentPane.add(label); contentPane.repaint(); try { Thread.sleep(300); // 0.3초 동안 잠을 잔다. if(flag==true) { contentPane.removeAll(); label = new JLabel("finish"); label.setLocation(100, 100); label.setForeground(Color.RED); return; // 스레드 종료 catch(InterruptedException e) { return; } 예제 13-5 flag를 이용한 스레드 강제 종료 public class ThreadFinishFlagEx extends JFrame { RandomThread th; // 스레드 레퍼런스 public ThreadFinishFlagEx() { setTitle("ThreadFinishFlagEx 예제"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(null); c.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { th.finish(); // RandomThread 스레드 종료 명령 } }); setSize(300,200); setVisible(true); th = new RandomThread(c); // 스레드 생성 th.start(); // 스레드 동작시킴 public static void main(String[] args) { new ThreadFinishFlagEx();

예제 실행 결과 스레드가 작동함 스레드가 종료하였음 컨텐트팬에 마우스를 클릭하면 스레드 종료

스레드 동기화(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 블록이 실행될 때, 먼저 실행한 스레드가 모니터 소유 모니터란 해당 객체를 독점적으로 사용할 수 있는 권한 모니터를 소유한 스레드가 모니터를 내놓을 때까지 다른 스레드 대기 void execute() { // 다른 코드들 // synchronized(this) { int n = getCurrentSum(); n+=10; setCurrentSum(n); } synchronized void add() { int n = getCurrentSum(); n+=10; setCurrentSum(n); } 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.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에 대한 두 스레드의 동시 접근 과정

집계판 예에서 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() 동기화 객체 두 개 이상의 스레드 사이에 동기화 작업에 사용되는 객체 동기화 메소드 synchronized 블록 내에서만 사용되어야 함 wait() 다른 스레드가 notify()를 불러줄 때까지 기다린다. notify() wait()를 호출하여 대기중인 스레드를 깨우고 RUNNABLE 상태로 만든 다. 2개 이상의 스레드가 대기중이라도 오직 한 스레드만 깨운다. notifyAll() wait()를 호출하여 대기중인 모든 스레드를 깨우고 모두 RUNNABLE 상 태로 만든다. wait(), notify(), notifyAll()은 Object의 메소드 모든 객체가 동기화 객체가 될 수 있다. Thread 객체도 동기화 객체로 사용될 수 있다.

Thread A가 ObjectS. wait()를 호출하여 무한 대기하고, Thread B가 ObjectS Thread A가 ObjectS.wait()를 호출하여 무한 대기하고, Thread B가 ObjectS.notify()를 호출하여 ObjectS에 대기하고 있는 Thread A를 깨운다. 4 개의 스레드가 모두 ObjectS.wait()를 호출하여 대기하고, ThreadA는 ObjectS.notify()를 호출하여 대기 중인 스레드 중 하나만 깨우는 경우 4 개의 스레드가 모두 ObjectS.wait()를 호출하여 대기하고, ThreadA는 ObjectS.notifyAll()를 호출하여 대기중인 4개의 스레드를 모두 깨우는 경우 잠자는 4개의 스레드 중 하나만 깨운다. 선택받지 못한 3 개의 스레드는 계속 잠을 잔다.

예제 13-6 : wait(), notify()를 이용한 바 채우기 public class TabAndThreadEx extends JFrame { MyLabel bar = new MyLabel(100); TabAndThreadEx(String title) { super(title); this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(null); bar.setBackground(Color.ORANGE); bar.setOpaque(true); bar.setLocation(20, 50); bar.setSize(300, 20); c.add(bar); c.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { bar.fill(); } }); setSize(350,200); setVisible(true); c.requestFocus(); ConsumerThread th = new ConsumerThread(bar); th.start(); // 스레드 시작 public static void main(String[] args) { new TabAndThreadEx( "아무키나 빨리 눌러 바 채우기"); import javax.swing.*; import java.awt.*; import java.awt.event.*; class MyLabel extends JLabel { int barSize = 0; // 바의 크기 int maxBarSize; MyLabel(int maxBarSize) { this.maxBarSize = maxBarSize; } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.MAGENTA); int width = (int)(((double)(this.getWidth())) /maxBarSize*barSize); if(width==0) return; g.fillRect(0, 0, width, this.getHeight()); synchronized void fill() { if(barSize == maxBarSize) { try { wait(); } catch (InterruptedException e) { return; } barSize++; repaint(); // 바 다시 그리기 notify(); synchronized void consume() { if(barSize == 0) { try { wait(); } catch (InterruptedException e) { return; } } barSize--; repaint(); // 바 다시 그리기 notify(); class ConsumerThread extends Thread { MyLabel bar; ConsumerThread(MyLabel bar) { this.bar = bar; public void run() { while(true) { sleep(200); bar.consume();

실행 결과 초기 화면 키를 반복하여 빨리 누른 화면