Issue

1. 동기와 비동기?

동기(Sync) : 하나의 작업을 끝낸 후 다른 작업을 다시 시작하는 방식을 의미한다

비동기(Async) : 하나의 작업이 끝나지 않더라도 다른 작업을 시작하는 방식을 의미한다

: 비동기 처리를 이용하면 동시적으로 작업을 수행할 수 있게 된다!

1) 자바에서의 동기 코드

public void sync() throws InterruptedException {
    System.out.println("작업1 시작");
    Thread.sleep(2000);
    System.out.println("작업1 종료");

    System.out.println("작업2 시작");
    Thread.sleep(2000);
    System.out.println("작업2 종료");
}

image.png

작업1은 작업2가 끝난 이후에 실행된다.

2) 자바에서의 비동기 코드

public void thread1() throws InterruptedException {
    new Thread(() -> {
        System.out.println("작업 1 시작");
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("작업 1 종료");
    }).start();

    System.out.println("작업 2 시작");
    Thread.sleep(1500);
    System.out.println("작업 2 종료");
}

image.png

작업1과 작업2는 랜덤하게 수행될 수 있으며 각각은 서로의 작업 완료를 신경쓰지 않는다.

3) Thread & Runnable