84. 프로그램의 동작을 스레드 스케줄러에 기대지 말라
// 스레드를 사용하는 간단한 예시
public class ThreadExample {
public static void main(String[] args) {
// 두 개의 스레드 생성
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("스레드 1 실행 중...");
try {
Thread.sleep(1000); // 1초 대기
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("스레드 2 실행 중...");
try {
Thread.sleep(1000); // 1초 대기
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 스레드 시작
thread1.start();
thread2.start();
}
}스레드 스케줄러에 의존하면 안 되는 이유
좋은 멀티스레드 프로그램 작성법
나쁜 예시
좋은 예시
피해야 할 것들
1. Thread.yield() 사용하지 않기
2. 스레드 우선순위에 의존하지 않기
좋은 방법과 나쁜 방법 비교
좋은 방법
나쁜 방법
정리
🧩 어려웠던 점
💡 느낀 점
Last updated