🤔 Thread에 대해 알아봅시다.
ex. 여러 사람(thread)이 함께 일(process)을 수행하면 더 빨리 끝낼 수 있는 것과 유사한 개념
: 여러 thread가 동시에 수행되는 프로그래밍, 여러 작업이 동시에 실행되는 효과
> thread는 각각 자신만의 작업 공간을 가짐 ( context )
> 각 thread 사이에서 공유하는 자원이 있을 수 있음 (자바에서는 static instance)
> 여러 thread가 자원을 공유하여 작업이 수행되는 경우 서로 자원을 차지하려는 race condition이 발생할 수 있음
> 이렇게 여러 thread가 공유하는 자원중 경쟁이 발생하는 부분을 critical section 이라고 함
⇒ critical section에 대한 동기화(일종의 순차적 수행) 구현이 필요
class MyThread extends Thread{
public void run() {
int i;
for(i = 0; i<200; i++) {
System.out.print(i + "\t");
}
}
}
public class ThreadTest {
public static void main(String[] args) {
System.out.println(Thread.currentThread());
MyThread th1 = new MyThread();
th1.start();
MyThread th2 = new MyThread();
th2.start();
}
}
class MyThread2 implements Runnable{
public void run(){
int i;
for(i=0; i<200; i++){
System.out.print(i + "\t");
}
}
}
public class ThreadTest2 {
public static void main(String[] args) {
System.out.println("main start");
MyThread2 mth = new MyThread2();
Thread th1 = new Thread(mth);
th1.start();
Thread th2 = new Thread(new MyThread2());
th2.start();
System.out.println("main end");
}
}
![]() | ![]() |
---|
▲ 동기적, 비동기적
병렬적 연산의 특징
1) 단시간 내 많은 양의 계산 가능
2) 시작하는 순서와 관계 없이 끝나는 순서를 통제할 수 없음
⇒ 비동기적 문제 해결을 위해 join 메소드 사용
참고자료 :
1. https://gitlab.com/easyspubjava/javacoursework/-/tree/master/Chapter6/6-20
2.
https://www.codelatte.io/courses/java_programming_basic/MML6WVLCE948OLD8