반응형

Concurrent 소프트웨어

  • 동시에 여러 작업을 할 수 있는 소프트웨어
  • 예) 웹 브라우저로 유튜브를 보면서 키보드로 문서에 타이핑을 할 수 있다.
  • 예) 녹화를 하면서 인텔리J로 코딩을 하고 워드에 적어둔 문서를 보거나 수정할 수 있다.

 

자바에서 지원하는 Concurrent 프로그래밍

  • 멀티프로세싱 (ProcessBuilder)
    • 어느 프로세스에서 다른 프로세스를 만드는 것이 가능하다.
  • 멀티쓰레드
    • 기본적으로 자바에서 메인 쓰레드 하나로 동작하지만 메인 쓰레드에서 다른 쓰레드를 만들 수 있다.

 

자바 멀티쓰레드 프로그래밍

  • 쓰레드 생성 방법
    • Thread 상속
    public static void main(String[] args) {
    	HelloThread helloThread = new HelloThread();
    	helloThread.start();
    	System.out.println("hello : " + Thread.currentThread().getName());
    }
    
    static class HelloThread extends Thread {
    	@Override
    	public void run() {
    		System.out.println("world : " + Thread.currentThread().getName());
    	}
    }
    • Runnable 구현 또는 람다
    Thread thread = new Thread(() -> System.out.println("world : " + Thread.currentThread().getName()));
    thread.start();
    System.out.println("hello : " + Thread.currentThread().getName());

 

쓰레드 주요 기능

  • 현재 쓰레드 멈춰두기 (sleep): 다른 쓰레드가 처리할 수 있도록 기회를 주지만 그렇다고 락을 놔주진 않는다. (잘못하면 데드락이 걸릴 수 있다)
  • 다른 쓰레드 깨우기 (interrupt): 다른 쓰레드를 깨워서 interruptedExeption을 발생 시킨다. 그 에러가 발생했을 때 할 일은 직접 정의한다.
    • 쓰레드를 종료 시킬 지, 계속 하던 일을 수행 시킬 지 판단 필요
  • 다른 쓰레드 기다리기 (join): 다른 쓰레드가 끝날 때까지 기다린다.

 

쓰레드 예제

public class Main {
    public static void main(String[] args) {
        /*
            과거의 쓰레드 사용 방법
            - 쓰레드가 늘어날 때마다 인터럽트 처리가 점점 늘어나고 복잡해진다.(문제)
               -> 수십, 수백개의 쓰레드를 코딩으로 직접 관리하는 것은 어렵다.
        */
        //1. Thread 인터페이스 구현
        Thread thread = new Thread(() -> {
            while(true){
                System.out.println("Thread1: " + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000L); //쓰레드를 sleep 시키면 다른 쓰레드가 먼저 일을 처리할 수 있게 된다.
                } catch (InterruptedException e) { //sleep 동안에 누군가가 이 쓰레드를 깨우면 발생.
                    //쓰레드가 interrupt 되었을 경우 작업 처리.
                    //쓰레드를 종료 시키거나, 별도의 동작을 수행하도록 할 수도 있다.
                    System.out.println("exit!");
                    return; //종료
                }
            }
        });
        thread.start();

        //2. Thread 클래스 상속
        MyThread myThread = new MyThread();
        myThread.start();

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

        try {
            myThread.join(); //메인 쓰레드는 thread2가 끝날 때까지 기다린다.
        } catch (InterruptedException e) {//메인쓰레드가 대기 중일 때 interrupt 되었을 경우 작업 처리.
            e.printStackTrace();
        }

        System.out.println(thread + " is finished");
        thread.interrupt(); //쓰레드를 깨우는 동작을 수행
    }

    static class MyThread extends Thread {
        @Override
        public void run() {
            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
            System.out.println("Thread2: " + Thread.currentThread().getName());
        }
    }
}

[참고자료]

더 자바, Java 8, 백기선

Lesson: Concurrency

Class Thread

반응형

+ Recent posts