package CHAP11;

//공유 자원 클래스 (동기화 처리 없음)
class Counter {
	int count = 0;

	// 동기화 처리 없는 증가 메서드
	public void increment() {
		count++; // 읽고 증가 → 중간에 다른 스레드가 끼어들 수 있음 (race condition 발생 가능)
	}
}

//카운터를 1000번 증가시키는 스레드
class HanThread extends Thread {
	Counter counter; // 공유 객체 참조

	public HanThread(Counter counter) {
		this.counter = counter;
	}

	public void run() {
		for (int i = 0; i < 1000; i++) {
			counter.increment(); // 동기화 없이 호출
		}
	}
}

public class C12_06_UnsynchronizedTest { // 동기화 없는 멀티스레드 실험 예제
	public static void main(String[] args) throws InterruptedException {
		Counter counter = new Counter(); // 공유 카운터 객체

		HanThread t1 = new HanThread(counter);
		HanThread t2 = new HanThread(counter);

		t1.start();
		t2.start();

		// 두 스레드가 끝날 때까지 대기
		t1.join();
		t2.join();

		// 예상값: 2000, 실제는 그보다 작을 수도 있음 (race condition)
		System.out.println("최종 카운트: " + counter.count);
	}
}