[OODP] Multi-thread

Peace·2021년 3월 24일
0

정리를 안한지 좀 오래됐다. 더 이상 복습을 게을리하지 않고, 다시 복습을 해서 업로드도 진행해야겠다.

Multithreading

먼저 multithreading에 들어가기전 concurrent programming과 parallel programming에 대해 간단히 알아보고 가겠다.

concurrent programming - concurrent programming은 말그대로 동시성을 의미한다. 많은 작업을 동시에 진행한다는 말이다. concurrent programming은 많은 수에 클라이언트에게 응답을 할 수 있으나, 실행시간은 보장하지 못한다.

parallel programming - parallel programming은 병렬로 진행되는 프로그래밍이다. 싱글 코어가 아닌 멀티 코어 이상인 컴퓨터에서 가능하다. concurrent programming처럼 동시에 작동하는 것처럼 보이는 것이 아닌, 실제로도 동시에 작동되고 있는 작업이다.

그럼 Thread란?

피피티에 내용을 빌리자면,

  • a sequential flow of execution
  • a sequence of control steps, executed one at a time, through a program
  • multiple threads my run at the same time in the same progrma (or process)

간단히 말하면 process의 실행 단위이다.

java에서 thread를 상속받아서 사용하는 방법도 있고, Runnable 인터페이스를 구현하는 방법이 있다.

Multithreaded program

하나의 프로그램에 동시에 여러 일을 할 수 있게 하는 프로그램을 말한다.

multithreading에서 가장 중요한 이슈는 synchronization이다.

두개의 thread가 동일한 data를 공유하기 때문에, 같이 접근한다면 문제가 생길 수 있다.

critical section에 lock을 이용하면 동시에 동일한 data에 접근하는 걸 방지하여, data corrupting을 막을 수 있다.

wait/notify
wait - 다른 thread가 작업을 끝나고, notify하기 전까지, thread를 wait하는 것이다.
notify - 기다리고 있는 thread에게 wait를 끝내도 된다고 알리는 것이다.

예제

예제는 하나만 보고 넘어가자.


Mediator class이다.
private boolean slotFull - 현재 slot 상태를 나타내는 member variable이다.

public synchronized void storeMessage() - 해당 method에 synchronized 키워드가 붙어있는데, synchronized는 스레드간 동기화를 시켜 현재 데이터에 사용하고 있는 thread외에 다른 thread들이 접근하지 못하도록 한다. synchronized 키워드를 너무 남발하면, 프로그램 성능 저하를 일으킬 수 있다.
그래서 해당 method는 말그대로 message를 저장하는 method인데, 슬롯에 message가 가득차있다면, 다른 thread가 message를 retrieve할 때까지 기다리고 있다가, 다른 thread가 찾아가고, notifyall을 해준다면, 그때 message를 저장할 수 있는 게 만들어진 method이다.

public synchronized int retrieveMessage() - storeMessage와 반대로 message를 retrieve하는 method이고, slot이 비어있으면, 아무것도 가져가지 못하기 때문에, wait하고, 다른 thread가 store하고, notifyAll를 해주면, 그때 가서 찾아가면 된다.

producer는 thread를 상속받는다.
Constructor는 Mediator instance를 받아, 저장한다.
run method는 thread의 run method를 오버라이딩한 것이다. 그래서 med instance에 storeMessage를 호출해 숫자를 저장하고 있다.

Consumer도 Producer와 크게 다를 것 없다. thread를 상속받고,
Constructor는 Mediator instance를 받아, 저장한다.
run method를 오버라이딩하고, retrieveMessage를 호출한다.

MediatorDemo는 main method가 들어있는 클래스이다.
Mediator instance를 하나 생성하고, producer 2개와 consumer 4개 instance를 만든 후, 동일한 Mediator instance를 parameter로 넘겨준다. 그래서 해당 instance들이 동일한 Mediator instance를 공유할 수 있도록 한다.
여기서 start라는 method를 사용한다.
start()메소드는 새로운 쓰레드가 작업을 실행하는데 필요한 호출스택(공간)을 생성한 다음 run()을 호출해서 그 안(스택)에 run()이 저장되는 것이다.

yield method

  • yields the currently executing thread so that any other runnable threads can run. The thread scheduler chooses the hightest-priority runnable thread to run.

현재 실행중인 thread가 가장 높은 우선 순위를 가진 runnable thread들에게 실행할 수 있도록 넘겨주는 method이다.

Reference

profile
https://peace-log.tistory.com 로 이사 중

0개의 댓글

관련 채용 정보