프로그래밍/Java
[자바/java] Thread. ThreadPool
Rolen
2023. 2. 3. 19:33
thread의 개수보다 작업의 개수가 더 많은 경우에는 작업은 FIFO Queue에서 대기한다.
Runnabel 객체를 구현하고 ThreadPoolExecutor로 보내기만 하면 됨. (ThreadPoolExecutor 는 thread로 실행하는 담당)
thread가 새로 생성되는 시간을 절약하며 ThreadPoolExecutor는 thread가 계속 생성되는 것을 방지하기 위하여
몇 개의 thread를 미리 생성한 후에 pooling하여 사용한다.
package threadPoolTest;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class ThreadPoolTest implements Runnable {
private String name;
public ThreadPoolTest(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void run() {
try {
System.out.println("실행중: " + this.name);
Thread.sleep((long)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2); // thread-pool의 크기 = 2
for (int i = 1; i <= 5; i++) {
ThreadPoolTest task = new ThreadPoolTest("작업: " + i);
System.out.println("작업생성: " + task.getName());
executor.execute(task);
}
executor.shutdown(); // shutdown() : 현재 처리중인 작업, 작업 큐에 대기하는 모든 작업을 완료한 뒤 종료
}
}
728x90