본문 바로가기
JAVA

221031 Semaphore

12.Dead Lock
=>결코 발생할 수 없는 사건을 무한정 기다리는 것
=>Synchronized 블럭이 여러 개 있는 경우에 멀티스레드를 사용하면 발생

13.Semaphore
=>상호배제를 하면서 동시에 사용할 수 있는 스레드의 갯수를 제한

=>Semaphore 클래스를 이용해서 설정

=>메서드
acquire() : 리소스를 확보하는 메서드
release() : 리소스를 해제하는 메서드


실습
1)세마포어를 이용하지 않는 경우-스레드가 동시에 전부 실행
=>4개 스레드가 10초후 동시에 메시지를 출력

 


2)세마포어를 이용하도록 수정

package java_1031.Semaphore;

import java.util.concurrent.Semaphore;

public class SemaphoreThread implements Runnable{
	
	String message;
	Semaphore semaphore;
	
	public SemaphoreThread(String message, Semaphore semaphore) {
		this.message=message;
		this.semaphore=semaphore;
	}
	
	@Override
	public void run() {
		try {
			//리소스 확보
			semaphore.acquire();
			Thread.sleep(10000);
			System.out.println(message);
		} catch (Exception e) {}
			//리소스 해제
		semaphore.release();
	}
	

}

 

main

package java_1031.Semaphore;

import java.util.concurrent.Semaphore;

public class SemaphoreMain {
	public static void main(String[] args) {
		Semaphore semaphore = new Semaphore(2);
		
		Thread th1 = new Thread(new SemaphoreThread("맥스",semaphore));
		Thread th2 = new Thread(new SemaphoreThread("아담",semaphore));
		Thread th3 = new Thread(new SemaphoreThread("피터",semaphore));
		Thread th4 = new Thread(new SemaphoreThread("해리슨",semaphore));
		Thread th5 = new Thread(new SemaphoreThread("메리",semaphore));
		
		
		th1.start();
		th2.start();
		th3.start();
		th4.start();
		th5.start();
		
		
		
	}
}
맥스
아담
메리
피터
해리슨

맥스

아담이 먼저 출력

10초 뒤에

메리

피터 출력

10초 뒤에

해리슨 출력 

Semaphore semaphore = new Semaphore(2);이므로,

스레드가 2개씩 사용되는 것

'JAVA' 카테고리의 다른 글

221031 Network  (0) 2022.10.31
221031 정규 표현식  (0) 2022.10.31
221031 생산자와 소비자 문제  (0) 2022.10.31
221031 MultiThread 실습  (0) 2022.10.31
221031 Thread2. Multi Thread  (0) 2022.10.31