자바

thread 활용방법

pipinstall 2023. 3. 15. 20:14
public class DataWriter implements Runnable {

  private int start;
  private int end;

  public DataWriter(int start, int end) {
    this.start = start;
    this.end = end;
  }

  @Override
  public void run() {
    for (int i = start; i < end; i++) {
      // 여기에서 데이터를 저장하는 로직을 추가합니다.
      System.out.println("Writing item: " + i);
    }
  }

}

public class Main {

  public static void main(String[] args) throws InterruptedException {

    final int TOTAL_DATA_COUNT = 10000;
    final int THREAD_COUNT = 3;
    final int DATA_PER_THREAD = TOTAL_DATA_COUNT / THREAD_COUNT;

    Thread[] threads = new Thread[THREAD_COUNT];

    for (int i = 0; i < THREAD_COUNT; i++) {
      int start = i * DATA_PER_THREAD;
      int end = (i + 1) * DATA_PER_THREAD;
      if (i == THREAD_COUNT - 1) {
        end = TOTAL_DATA_COUNT;
      }
      DataWriter writer = new DataWriter(start, end);
      threads[i] = new Thread(writer);
      threads[i].start();
    }

    for (int i = 0; i < THREAD_COUNT; i++) {
      threads[i].join();
    }

  }

}

위 코드는 DataWriter 클래스와 Main 클래스로 구성되어 있습니다.

DataWriter 클래스는 Runnable 인터페이스를 구현하여 run() 메서드를 오버라이드합니다. 이 클래스는 start와 end 값을 인자로 받아서 start부터 end 직전까지의 데이터를 저장하는 로직을 run() 메서드에서 구현합니다.

Main 클래스는 TOTAL_DATA_COUNT, THREAD_COUNT, DATA_PER_THREAD 변수를 설정하여 총 데이터 수, 스레드 수, 스레드 당 처리할 데이터 수를 지정합니다.

Main 클래스는 threads 배열을 생성하여 각 스레드를 저장합니다. 이후, for 루프를 사용하여 스레드를 생성하고 시작합니다. DataWriter 객체를 생성하여 각 스레드에 전달하고, start() 메서드를 호출하여 스레드를 시작합니다.

마지막으로, Main 클래스는 각 스레드가 종료될 때까지 join() 메서드를 호출하여 대기하고, 모든 스레드가 종료된 후에 프로그램을 종료합니다.

이 예제 코드는 10000개의 데이터를 3개의 스레드로 분할하여 저장하는 예제입니다. 각 스레드는 3333개씩의 데이터를 저장하며, 마지막 스레드는 3334개의 데이터를 저장합니다. 실행 결과는 콘솔에 "Writing item: 0" ~ "Writing item: 9999"라는 10000개의 출력문으로 나타납니다.