티스토리 뷰

CompletableFuture를 알기 전에 Concurrent 프로그래밍을 꼭 알아야 한다.

Concurrent 소프트웨어란 말 그대로 동시에 여러 작업을 할 수 있는 소프트웨어를 뜻한다.

자바에서는 다음과 같은 Concurrent 프로그래밍을 지원한다.

  • 멀티프로세싱 (ProcessBuilder)
  • 멀티쓰레드

멀티쓰레드

디폴트 쓰레드는 Main이라는 이름을 가진다.

public class App  {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName());
    }
}

// 실행결과
main

다음으로는 쓰레드를 직접 만드는 방법을 살펴보자.

1. 상속

public class App  {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();

        System.out.println("Hello: " + Thread.currentThread().getName());
    }

    static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("Thread: " + Thread.currentThread().getName());
        }
    }
}

위 코드처럼 Thread를 상속받아서 직접 만들 수 있다.

2. Runnable()

public class App  {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> System.out.println("Thread: " + Thread.currentThread().getName()));
        thread.start();
        System.out.println("Hello: " + Thread.currentThread().getName());
    }
}

1번과 2번 같은 경우는 아래 사진처럼 출력 결과가 제각각일 수 있다.

🤔 순서를 정해줄 수는 없을까?

 

첫 번째로는 Thread의 기능인 sleep으로 가능하다.

  • sleep : 다른 쓰레드가 처리할 수 있도록 기회를 줄 수 있다.
public class App {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread: " + Thread.currentThread().getName());
        });
        thread.start();
        System.out.println("Hello: " + Thread.currentThread().getName());
    }
}

락의 문제가 있다. ⇒ 데드락의 원인

두 번째로는 Thread의 기능인 join으로 가능하다.

  • join : 다른 쓰레드가 끝날 때까지 기다린다.
public class App {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            System.out.println("Thread: " + Thread.currentThread().getName());
            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                System.out.println("interrupted");
                return;
            }
        });
        thread.start();
        System.out.println("Hello: " + Thread.currentThread().getName());
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(thread.getName() + " is finished");
    }
}

🤔 시간을 기다려야만 해당 쓰레드를 사용할 수 있을까?

Thread의 기능인 interrupt를 통해 잠자는 쓰레드를 깨울 수 있다.

public class App {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            while (true) {
                System.out.println("Thread: " + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    System.out.println("interrupted");
                    return;
                }
            }
        });
        thread.start();
        System.out.println("Hello: " + Thread.currentThread().getName());
        Thread.sleep(3000L);
        thread.interrupt();
    }
}

주의할 점은 interrupt라는 메서드는 쓰레드를 종료시키는 게 아닌 InterruptedException을 발생시켜주는 것이다.

그러므로 InterruptedException 이후에 처리는 catch 문에 직접 코딩해야 한다.

멀티 쓰레드일 때 문제점이 바로 이러한 점들 때문이다.

예제에서는 두 개의 쓰레드로 했지만 여러 개로 이루어진 멀티 쓰레드 환경에서 프로그래머가 코딩으로 직접 관리하기엔 너무 복잡하다.

그렇기 때문에 Executors 그리고 Future라는 걸 사용한다.

'JAVA' 카테고리의 다른 글

java에서 멀티쓰레드 [3] Callable과 Future  (0) 2022.02.07
java에서 멀티쓰레드 [2] Executors와 ExecutorService  (0) 2022.02.07
Consumer  (0) 2022.02.04
Disposable  (0) 2022.02.04
map vs flatMap in stream  (0) 2022.02.04
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함