관리 메뉴

cococo-coding

[Java] 멀티스레드와 동기화 본문

개인공부/자료구조

[Java] 멀티스레드와 동기화

_dani 2024. 2. 13. 09:38

멀티쓰레드란?

https://www.geeksforgeeks.org/difference-between-multiprocessing-and-multithreading/

 

하나의 프로세스 내에서 둘 이상의 스레드가 동시에 작업을 수행하는 형태

  • 프로세스(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/

 

Difference between Multiprocessing and Multithreading - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

'개인공부 > 자료구조' 카테고리의 다른 글

01. 자료구조와 알고리즘  (0) 2024.02.01