17_java_쓰레드(Thread) 동기화

study/java · 2022. 1. 21. 08:39

○ 임계영역(critical section)
다른 쓰레드가 동시에 끼어들어 사용하지 말아야하는 영역

○ intrinsic lock(monitor lock)
임계영역에 쓰레드가 사용 중일 때 다른 쓰레드가 접근하지 못하게 하는 잠금 장치
모든 객체 내부에 존재함

○ 기본적인 동기화
static Object lockIndex = new Object();

// lock으로 잠금을 해야하는 상황
synchronized (lockIndex) {
임계영역
}

○ 메소드 단위의 동기화

public synchronized void 함수명() {
	Thread th = Thread.currentThread();
		
	char ch = list[index];
		
	try {
		Thread.sleep(20);
	} catch (InterruptedException e) {
		System.err.println("자다깨서 쓰레드를 종료함");
		return;
	}
	
	//synchronized (this) {
		System.out.printf("%s[%d] : index:%d, char:%c\n",  
				th.getName(), th.getId(), index, list[index]);
		index++;
	//}
}

-> 메소드 단위로 임계영역을 지정하기 때문에 불필요한 부분까지 임계영역으로 잡혀 성능이 저하됨

'study > java' 카테고리의 다른 글

16_java_쓰레드(Thread)_사전지식, 왜?  (0) 2022.01.07
15_java_복습_Generic  (0) 2022.01.05
14_java_입출력(IO)  (0) 2019.11.29
13_java_Exception  (0) 2019.11.28
14_java_용어정리  (0) 2019.11.13