[Java] 스레드(Thread)

Updated:

프로세스(process) 내에서 실제로 작업을 수행하는 주체

프로세스(process) & 스레드(thread)


프로세스(process)

  • 실행 중인 프로그램(program)
  • 운영체제에서 메모리 공간을 할당받아 실행 중인 것
  • 프로그램 데이터, 메모리 등 자원, 스레드로 구성

스레드(thread)

  • 프로그램 실행 흐름
  • 모든 프로세스에는 한 개 이상의 스레드가 존재
    • 싱글 스레드(single thread program) : 스레드가 하나뿐인 프로그램
    • 멀티스레드 프로그램(multithread program) : 스레드가 둘 이상인 프로그램. 여러 클라이언트에게 들어오는 메시지를 동시에 처리.
      • 입금과 출금이 동시에 진행될 때
  • 각각의 스레드는 서로가 생성한 객체를 공유 가능.
  • 동시성, 동기화 문제를 해결해줘야함

스레드의 생성과 실행


Thread 클래스 이용

  1. Thread Class를 상속 받은 Class를 하나 만듦
  2. run() 메서드를 overriding하여 수행할 일을 코딩해준다.
  3. main thread 에서 a 단계에서 만든 Class의 start() 메서드를 호출한다. start() : main 스레드가 아닌 별도로 만들어진 thread에서 처리한다는 것)

Runnable 인터페이스 이용

  • Runnable 인터페이스는 구현할 메소드가 run() 하나인 메소드
  • 람다를 이용하면 단순화 가능

사용 예제

class ThreadWithClass extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++)
            System.out.println(getName()); // 현재 실행 중인 스레드의 이름을 반환함.
            try {

                Thread.sleep(10);          // 0.01초간 스레드를 멈춤
            } catch (InterruptedException e) {
                e.printStackTrace();

            }
        }
    }
}

class ThreadWithRunnable implements Runnable {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName()); // 현재 실행 중인 스레드의 이름을 반환함.
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class Thread01 {
    public static void main(String[] args){
        ThreadWithClass thread1 = new ThreadWithClass();       // Thread 클래스를 상속받는 방법
        Thread thread2 = new Thread(new ThreadWithRunnable()); // Runnable 인터페이스를 구현하는 방법
        thread1.start(); // 스레드의 실행
        thread2.start(); // 스레드의 실행
    }
}

참고


  • https://www.tcpschool.com/java
  • https://www.daleseo.com/java-thread-runnable/

Tags:

Categories:

Updated:

Leave a comment