w ho
4 min readJan 29, 2020

thread 이해하기

thread

#Thread 의 이해

  • thread 와 프로세스 차이가 무엇인가 ?

하나의 프로그램이 실행 되고 있을때 그 실행 되고 있는 흐름을 프로세스라 한다.

하나의 프로세스는 여러 작업에 관여 할 수 있고 그것을 병렬적 수행 이라고 한다. 컴퓨터에서 코어 같은 느낌

thread 는 프로세스 안에서 일을 하는 요소라고 생각하면 된다.

예를 들어 요리를 할 때 메뉴 하나하나가 프로세스이고 햄버거를 만드는 프로세스에서 햄버거 패티를 굽는 thread 야채를 볶는 thread 이런식으로 생각하면됨.

자바로 간단한 예제 구현

public class ReamonProgram {public static void main(String[] args) {try {RamenCook ramenCook =new RamenCook(6);new Thread(ramenCook,"A").start();new Thread(ramenCook,"B").start();new Thread(ramenCook,"C").start();new Thread(ramenCook,"D").start();} catch (Exception e) {e.printStackTrace();}}}class RamenCook implements Runnable {private int ramenCount;private String[] burners = {"_","_","_","_"};public RamenCook(int count){ramenCount =count;}@Overridepublic void run() {while(ramenCount >0){synchronized (this) {  // 한번에 한 쓰레드만 접근 가능하게ramenCount--;System.out.println(Thread.currentThread().getName()+":"+ramenCount);}for(int i=0;i<burners.length;i++){if(!burners[i].equals("_")) continue; // 버너가 비어있는 것을 찾아 그 버너에 해당 쓰레드를 넣는다 .synchronized (this) {burners[i] = Thread.currentThread().getName();System.out.println(Thread.currentThread().getName()+":"+(i+1)+"번ON");
showBurners();
}try {Thread.sleep(2000);} catch (Exception e) {e.printStackTrace();}synchronized (this) {burners[i]="_";System.out.println(Thread.currentThread().getName()+":"+(i+1)+"OFF");
showBurners();
}
break;
}try {Thread.sleep(Math.round(1000 * Math.random()));} catch (Exception e) {e.printStackTrace();}}}private void showBurners() {String StringToPrint="";for(int i=0;i<burners.length;i++){StringToPrint +=(" "+burners[i]);}System.out.println(StringToPrint);}}

실행 결과

A B C D라는 쓰레드가 각각 의자리에서 일을 하는걸 확인

오늘의 결론

Thread를 이해하였고, 동기화인 critical section 동기화 synchronized 를 통해서 하나의 작업을 하나의 쓰레드가 할수 있게 돕는다.

No responses yet