자바 공부 27 : 스레드

친환경 개발자
|2024. 3. 2. 23:15

스레드란?

한 프로세스 내에서 두 가지 이상의 일을 동시에 수행하는 것

      *프로세스: 동작하고 있는 프로그램을 말함

 

 

 

 

스레드 구현 시 필수 사용 메서드

  • run() : Thread를 상속할 경우 필수적으로 구현해야 함. 동시에 수행할 코드들을 입력하는 곳
  • start() : 스레드를 실행할 때 사용

 

    <예시>

public class Day24 extends Thread {
   public void run() {     // Thread를 상속하면 run 메서드를 구현해야 함
        System.out.println(this.seq + "thread start.");     //스레드 시작
        try {
             Thread.sleep(1000);     //1초 대기한다.
         } catch (Exception e) {
         }        System.out.println(this.seq + "thread end.");     //스레드 종료
    }

  public static void main(String[] args) {
       for (int i=0; i<10; i++) {      // 총 10개의 스레드를 생성하여 실행한다.
           Thread t = new Day24(i);
           t.start();    // start로 스레드를 실행
       }
        System.out.println("main end.");   // main메서드 종료

        → 0~9까지 동시에 실행되어 무작위 순서로 출력됨


 

Join 메서드

스레드가 모두 종료된 후 다음 작업을 진행해야 할 때 반드시 사용

스레드가 종료되지 않았는데 다음 작업을 진행 시 오류 발생 가능성 높아짐.

 

import java.util.ArrayList;     // Join메서드 사용 시

public class Day24 extends Thread {
    int seq;

    public Day24(int seq) {
        this.seq = seq;
    }

    public void run() {     
        System.out.println(this.seq + "thread start.");     //스레드 시작
        try {
            Thread.sleep(1000);     //1초 대기한다.
        } catch (Exception e) {
        }
        System.out.println(this.seq + "thread end.");     //스레드 종료
    }

    public static void main(String[] args) {
        ArrayList<Thread> threads = new ArrayList<>();  //
        for (int i=0; i<10; i++) {
            Thread t = new Day24(i);
            t.start();
            threads.add(t);
        }

        for (int i=0; i<threads.size(); i++) {
            Thread t = threads.get(i);
            try {
                t.join();       // 스레드가 종료할 떄까지 기다린다.
            } catch (Exception e) {
            }
        }
        System.out.println("main end.");
    }

 

 

 

Runnable 인터페이스 (Thread 상속 대신)

보통 Thread를 상속하기보단 Runnable인터페이스를 사용

 

Thread클래스를 상속 시 다른 클래스를 상속하지 못하기 때문

 

Runnable 인터페이스 사용 시 더 유연한 프로그램 제작 가능

 

import java.util.ArrayList; 


public class Day24 implements Runnable{
    int seq;

    public Day24(int seq) {
        this.seq = seq;
    }

    public void run() {     
        System.out.println(this.seq + "thread start.");    
        try {
            Thread.sleep(1000);   
        } catch (Exception e) {
        }
        System.out.println(this.seq + "thread end.");    
    }

    public static void main(String[] args) {
        ArrayList<Thread> threads = new ArrayList<>();
        for (int i=0; i<10; i++) {
            Thread t = new Thread(new Day24(i));
            t.start();
            threads.add(t);
        }

        for (int i=0; i<threads.size(); i++) {
            Thread t = threads.get(i);
            try {
                t.join();  
            } catch (Exception e) {
            }
        }
        System.out.println("main end.");
    }
}