일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
- git #unity #깃허브
- flutter #깃
- 로컬저장소 #이름변경
- flutter #git
- 비주얼 스튜디오 #vs #visual studio
- 비주얼스튜디오 #코드스니펫
- baekjoon #백준 #boj
- flutter #todolist
- 유데미 #udemy #웅진씽크빅 #스나이퍼팩토리 #인사이드아웃 #미래내일일경험 #프로젝트캠프 #부트캠프 #react #리액트프로젝트 #프론트엔드개발자양성과정 #개발자교육과
- flutter #플러터 #분석
- unity #2d-game
- unity #2d-game #minigame #vscode
- Flutter
- 백준 #boj
- 플러터 #flutter #restful #rest api
- flutter #상태관리
- flutter #firebase #플러터 #파이어베이스 #연동
- 백준 #boj #baekjoon
- boj #baekjoon #c++
- boj #baekjoon
- firebase #파이어베이스
- baekjoon #boj #c++
- 인턴 #프론트엔드 #개발자 #프론트엔드개발자 #취준
- flutter #app #취준
- boj #c++
- 백준
- flutter #플러터
- #유데미 #udemy #웅진씽크빅 #스나이퍼팩토리 #인사이드아웃 #미래내일일경험 #프로젝트캠프 #부트캠프 #react #리액트프로젝트 #프론트엔드개발자양성과정 #개발자교육과정
- 백준 #c++
- VS #비주얼스튜디오
- Today
- Total
cococo-coding
[Java] 멀티스레드와 동기화 본문
멀티쓰레드란?
하나의 프로세스 내에서 둘 이상의 스레드가 동시에 작업을 수행하는 형태
- 프로세스(Process): 실행 중인 프로그램을 뜻하며, 사용자가 os로부터 메모리공간을 할당받아 실행함.
- 스레드(Thread) : 프로세스 내에서 실제 작업을 수행하며, 모든 프로세스는 최소 하나의 스레드를 가짐.
스레드 생성하기
스레드는 Thread 클래스를 상속하는 방법과 Runnable 인터페이스를 구현하는 방법으로 생성한다.
1) Thread 클래스 상속
//스레드 클래스 상속
public class showThread extends Thread{
@override
public void hello(){
System.out.println("스레드클래스 상속");
}
}
//스레드 실행_객체 인스턴스 생성후 start메소드 호출
public static void main(String[] args) {
showThread thread = new showThread();
thread.start();
}
}
2) Runnable 인터페이스 구현
//runnable 인터페이스 구현
public class helloRunnable implements Runnable {
@override
public void hello() {
System.out.println("hello");
}
}
//스레드 실행_객체 인스턴스 전달 후 start() 메소드 호출
public static void main(String[] args) {
helloRunnable runnable = new helloRunnable();
Thread thread =new Thread(runnable);
thread.start();
}
}
Thread 클래스를 상속받는 방식은 다양한 메서드를 재정의할 수 있다는 장점이 있고, Runnable 인터페이스는 다형성과 메모리를 아낄 수 있다는 장점이 있다.
멀티쓰레드 동기화란? (Thread Synchronization)
멀티스레드 프로세스 환경에서 한 스레드가 진행 중인 작업에 다른 스레드가 간섭하지 못 하도록 막는 것이다.
두 개 이상의 스레드가 공유 데이터에 동시에 접근할 때 발생하는 문제를 해결할 수 있다.
구현하는 방법
: synchronized 키워드로 임계 영역(cirtical section) 과 락(lock) 을 설정하여 멀티쓰레드 동기화를 구현할 수 있다. 만약 스레드가 임계 영역에 접근하게 되면 Lock을 얻게 된다. 이후 해당 스레드가 Lock을 반납하기 이전까지 다른 스레드가 해당 임계 영역에 접근하지 못 하게 된다.
- 임계 영역(cirtical section)은 둘 이상의 스레드가 동시에 접근불가한 코드 영역
- 락(lock)은 임계 영역을 포함하고 있는 개체에 대한 접근권한
이때 임계 영역은 메서드 전체나 특정코드 블록으로 설정가능하다.
1) 메서드 전체
synchronized 키워드를 해당 메서드의 반환 타입 앞에 입력한다.
public synchronized void hello(int value) {
....
코드
....
}
2) 특정코드 블록
synchronized 키워드를 작성하고 해당 블록을 지정한다. 참조변수(this) 객체에 lock을 사용할 수 있다.
public void hello (int value) {
synchronized (this) {
....
코드
....
}
}
출처:
https://www.geeksforgeeks.org/difference-between-multiprocessing-and-multithreading/
'개인공부 > 자료구조' 카테고리의 다른 글
01. 자료구조와 알고리즘 (0) | 2024.02.01 |
---|