스레드 생성1

public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(
                /*() -> {
                    System.out.println("We are in thread : " + Thread.currentThread().getName());
                    System.out.println("Current thread priority is " + Thread.currentThread().getPriority());
                }*/
                new Runnable() {
                    //생성된 스레드가 실행할 코드 작성
                    @Override
                    public void run() {
                        System.out.println("We are in thread : " + Thread.currentThread().getName());
                        System.out.println("Current thread priority is " + Thread.currentThread().getPriority());
                    }
                });

        thread.setName("New Worker Thread");
        //스레드의 우선순위 설정 1~10의 값을 줘야 한다. (상수 이용 가능)
        thread.setPriority(Thread.MAX_PRIORITY);
        System.out.println("We are in thread : " + Thread.currentThread().getName() + " before starting a new thread");
        //이 때 jvm이 새 스레드를 생성해 운영체제에 전달
        thread.start();
        System.out.println("We are in thread : " + Thread.currentThread().getName() + " after starting a new thread");
    }
/*
출력 :
We are in thread : main before starting a new thread
We are in thread : main after starting a new thread
We are in thread : New Worker Thread
Current thread priority is 10
*/
  • 스케줄링에 의해 새로 생성된 스레드는 main뒤에서 실행되었다. 만약 start()호출 이후 아래에 sleep()을 호출하면 스레드가 먼저 실행되게 된다.
  • setName()으로 스레드의 이름을 지정하지 않으면 생성된 스래드의 이름은 Thread-0와 같이 의미없는 이름으로, 스레드 개수가 많은 애플리케이션에선 의미 있는 스레드 이름이 추후에 디버깅할 때 큰 도움이 된다.
  • 람다식을 사용하자.

 

스레드 생성2

public static void main(String[] args) {
    Thread thread = new NewThread();
    thread.start();
}
private static class NewThread extends Thread{
    @Override
    public void run() {
        System.out.println("hello from " + this.getName());
    }
}
  • 이렇게 하면 this를 통해 thread의 데이터를 가져올 수 있다.
  • 오버라이딩을 통해 공통된 기능을 설정 후 상속 기능을 이용할 수 있다.
상속할 일이 있을 거 같으면 2번, 없으면 1번의 방식을 사용하자.

 

스레드 예외 핸들러

public static void main(String[] args) {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            throw new RuntimeException("Internal Exception");
        }
    });

    thread.setName("Misbehaving thread");
    thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println("A critical error happened in thread " + t.getName()
                    + " the error is " + e.getMessage());
        }
    });
    thread.start();
}
  • 기본적으로 java에서 예외가 발생했을 때 이 예외를 처리하지 않으면 모든 스레드, 프로그램이 종료된다.
  • 개별 스레드에서 발생한 예외를 처리하지 않았을 때 처리해줄 개별 handler를 처음부터 설정할 수 있다.

'JAVA > 멀티스레딩' 카테고리의 다른 글

락킹 심화  (0) 2024.08.29
병행성 문제와 솔루션  (0) 2024.08.29
멀티 스레드 주의 사항(병행성 문제)  (0) 2024.08.29
Thread Pooling  (0) 2024.08.28
스레드 조정  (0) 2024.08.28

+ Recent posts