강의

멘토링

커뮤니티

Inflearn Community Q&A

jeongik229381770's profile image
jeongik229381770

asked

Kim Young-han's Practical Java - Advanced, Part 1: Multithreading and Concurrency

6. synchronized 문제 1 log출력

Written on

·

178

1

public static void main(String[] args) throws InterruptedException {
    Counter counter = new Counter();

    Runnable task = new Runnable() {

        @Override
        public void run() {
            for (int i = 0; i < 10000; i++) {
                counter.increment();
                log(counter.getCount()); // 로그 출력 추가!!!!!!!!!!!!!!!
            }
        }
    };

    Thread thread1 = new Thread(task);
    Thread thread2 = new Thread(task);

    thread1.start();
    thread2.start();
    thread1.join();
    thread2.join();
    log(counter.getCount());
}

static class Counter {

    private int count;

    public void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

문제를 푸는 도중 count의 값을 확인해보고 싶어서 MyLogger.log(counter.getCount());를 호출했더니 문제 없이 20000이 계속 출력됩니다.

synchronized를 사용하지 않아서 여전히 동시성 문제는 발생할텐데 어떻게 20000이라는 값이 나오게 되는지 궁금합니다!!

 

java객체지향동시성multithreadthread

Answer 1

3

아마 요즘 컴들은 성능이 좋아서 그래요 10000대신 100_000_000L로 해보시겠어요?

감사합니다!!

jeongik229381770's profile image
jeongik229381770

asked

Ask a question