개념 정리
멀티 스레딩 (Multi-Threading)이란?
멋진놈
2023. 10. 27. 16:05
728x90
멀티 스레딩은 하나의 프로세스 내에서 여러 개의 스레드가 동시에 실행되는 것을 의미함.
이는 프로세스 내의 각 스레드가 공유 메모리 공간을 가지며, 각 스레드는 독립적으로 실행됨.
장점 : 멀티 스레딩은 여러 작업을 동시에 처리하고 병렬로 실행할 수 있는 장점을 가짐.
예를 보자
public class MultiThreadExample {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable("Thread 1"));
Thread thread2 = new Thread(new MyRunnable("Thread 2"));
thread1.start(); // 스레드 1 시작
thread2.start(); // 스레드 2 시작
}
}
class MyRunnable implements Runnable {
private String name;
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(name + ": " + i);
}
}
}
출력 결과
Thread 1: 1
Thread 2: 1
Thread 1: 2
Thread 2: 2
Thread 1: 3
Thread 2: 3
Thread 1: 4
Thread 2: 4
Thread 1: 5
Thread 2: 5
1. thread1에 MyRunnable이 받는다. 그것을 thread1.start()로 스레드를 시작한다.
2. thread2도 마찬가지로 그렇게 실행된다.
3.this.name에 해당 Thread 1과 Thread 2를 넣어준다.
4. implements Runnable을 받고 있기 때문에, 반드시 자식이 run() 메서드를 오버라이딩 해야함.
5. 받은 것을 for로 돌아가면서 각각 i가 5가 될떄 까지 뿌려줌.
만약에 Thread 1과 Thread 2가 자리를 바꾸면 출력 결과는 뒤 바뀐다.
이렇게 하나의 프로세스 내에서 동시에 실행 되는 것이 멀티 스레딩이다.