스레드를 구현할 수 있는 대표적인 3가지 방안에 대해 공부한 내용을 기록한다.
MyThread mt = new MyThread();
mt.run();
Runnable mt = new MyThread2();
Thread thread = new Thread(mt);
thread.start();
(* 이때 Runnable 객체를 Thread의 인자로 전달하여 스레드를 구현할 수 있다.)
Runnable task = () -> {
int sum = 0;
for(int i = 0 ; i < 100 ; i++) {
sum += i;
System.out.println(sum);
}
System.out.println(Thread.currentThread().getName() + " : " + sum);
};
//task 정보를 스레드에 전달
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.setName("thread1");
thread2.setName("thread2");
thread1.start();
thread2.start();
위 멀티스레드를 실행하면 아래와 같은 로그를 확인할 수 있다.
0
1
3
6
10
15
21
28
0
1
3
6
10
15
21
28
36
45
55
66
36
45
55
66
78
91
0 - 1 - 3 - 6으로 진행하는 sum의 과정이 일련의 연속적인 작업로그로 출력되지 않고, 병렬적으로 실행되어 중간에 0 - 1 - 3- 6의 로그가 출력되는 것을 확인할 수 있다.
즉, 작업의 순서/시작/끝을 정확하게 예측할 수 없으므로 멀티스레드를 활용한 작업 시 반드시 각 스레드 간의 순서를 보장하기 위한 작업을 진행해야 한다.
이 작업이 바로 동기화 작업이다.