[Java] 스레드(Thread)

Hyo Kyun Lee·2022년 2월 3일
0

Java

목록 보기
41/49

1. 스레드

Thread, 프로세스 내부적으로 동작하는 여러 개의 하위 프로세스를 의미한다.

운영체제(OS)는 하드웨어를 사용할 수 있도록 내부적인 프로그램을 동작하게하는 주체이자 처리시스템이다.

Java를 실행하도록 하는 JVM은 하나의 운영체제처럼 작동하여, 이와 유사한 원리로 여러가지 프로세스를 동작시킬 수 있다.
이때 동작하는 하위 프로세스들을 스레드라 일컫고, 이 스레드 작업을 통해 여러개의 작업을 처리할 수 있게 된다.

2. 스레드 생성

Java 프로그래밍을 하면서 스레드를 생성하는 목적은 main thread 외에 다른 스레드, 즉 실행하고자 하는 또 다른 클래스를 생성해내는 것에 있다.

스레드 생성은 Thread class를 상속받아서 해당 메소드를 사용하는 것으로 부터 구현할 수 있는 방법이 있고, Runnable 인터페이스를 통한 구현 방법이 있다.

2-1. Thread class 상속을 통한 스레드 생성

2-1-1. Thread를 상속받는 sub thread 클래스 생성

  • 생성자 입력 및 Thread 메소드 중 run() 메소드를(오버라이딩) 통해 스레드 생성
    ※ 스레드 내부에서 실행하고자 하는 구문을 작성
public class MyThread extends Thread{
	String str;
    
    //생성자 생성
    public MyThread(String str){
		this.str = str;
    }
    
    //run method 오버라이드
    @Override
    public void run(){
    	System.out.println(str);
        Thread.stop(200);
    }
}

2-1-2. main class(Thread)에서 sub thread 실행

  • main thread에서 sub thread를 실행하도록 구성, sub thread 호출은 start() 메소드를 사용하여 호출한다.
public class ThreadStart{
	public void main(String[] args){
		//스레드 클래스 생성
        MyThread th1 = new MyThread("*");
        MyThread th2 = new MyThread("!");
        
        //이후 subthread를 실행(sub thread의 run 메소드를 실행)
    	th1.start();
        th2.start();
    }
}

※ 메인스레드와 함께, 신규로 생성된 sub thread 들이 완전히 종료되어야 프로그램이 종료된다.

2-2. Runnable 인터페이스를 통한 스레드 생성

java는 단일 상속만을 지원하기 때문에, 하나의 class만 상속받을 수 있다.
따라서 일전의 상속 방법으로 구현할 수 없는 상황에서는 Runnable 인터페이스를 설정해주는 방법을 통해 구현한다.

2-2-1. Ruunable interface를 적용한 sub thread 정의

superclass(상속)을 사용하지 않고, interface에 Runnable을 설정해주도록 한다.

이외 thread를 작성해주는 과정은 Runnable 인터페이스를 구성해주는 것 외에는 동일하다.

public class MyThread implements Runnable{
	String str;
	public MyThread(str){
    	this.str = str;
    }
    
    @Override
    public void run(){
    	System.out.println(str);
    }
}

2-2-2. main thread 생성 및 sub thread 호출

위에서 정의한 sub thread를 main thread에서 실행한다.
다만 해당 thread들은 thread를 상속받아 구현한 것이 아닌, Runnable() 인터페이스를 구현한 것이므로 start 메소드를 바로 활용할 수는 없다.

start 메소드를 사용하기 위해 thread 객체를 만들고 생성자를 초기화해주고, 이후엔 start 메소드를 사용함으로써 run() 메소드 호출 및 스레드를 실행시킬 수 있다.

public class ThreadTest{
	public void main(String[] args){
    	MyThread th1 = new MyThread();
        MyThread th2 = new MyThread();
        
        //Thread 객체 생성
        Thread thread1 = new Thread(th1);
        Thread thread2 = new Thread(th2);
        
        //스레드 실행
        thread1.start();
        thread2.start();
    }
}

3. 참조자료

프로그래머스 강의 - 스레드
https://programmers.co.kr/learn/courses/9/lessons/270

프로그래머스 강의 - 스레드 생성
https://programmers.co.kr/learn/courses/9/lessons/271
https://programmers.co.kr/learn/courses/9/lessons/272

0개의 댓글