스레드 풀
미리 여러 개의 스레드를 생성하고 미리 스레드 풀에 넣고 사용시 직접 가져와 사용 후 다시 풀에 넣습니다. 빈번한 생성 및 파괴를 피하고 재사용을 실현할 수 있습니다.
이익
- 응답 속도 향상
- 자원 소비 감소
- 스레드 관리 촉진
- corePoolSize : 코어 풀의 크기
- maximunPoolSize : 최대 스레드 수
- keepAliveTime : 유지 시간
1. 집행자 서비스
public interface ExecutorService
extends Executor
Executor
관리 단말 및 방법이 진행을 생성하는 하나 개 이상의 비동기 태스크 추적 할 수 Future
방법을 제공한다.
하나 ExecutorService
를 닫으면 새 작업이 거부됩니다. 닫기를 위해 ExecutorService
두 가지 다른 방법이 제공됩니다 . 이 메서드를 사용하면 shutdown()
이전에 제출 된 작업이 실행 전에 종료 될 수 있으며,이 shutdownNow()
메서드는 현재 실행중인 작업을 중지하려는 작업이 시작될 때까지 기다리는 것을 방지합니다. 종료시 실행자는 활성 작업, 실행 대기중인 작업, 제출할 새 작업이 없습니다. 사용하지 않는 항목 ExecutorService
은 리소스를 복구 할 수 있도록 닫아야합니다.
메서드 submit
확장 메서드베이스 Executor.execute(Runnable)
는 Future
실행을 취소하거나 완료를 기다릴 수 있는 메서드를 만들고 반환합니다 . 메서드 invokeAny
및 invokeAll
실행 본문 실행의 가장 일반적인 형태, 수행 된 작업 모음, 그리고 적어도 하나 또는 모두가 완료 될 때까지 대기합니다. (클래스 ExecutorCompletionService
를 사용하여 이러한 메서드를 작성할 수 있습니다. 사용자 지정 변형)
이 Executors
클래스는이 패키지에서 제공하는 실행 서비스의 팩토리 메소드를 제공합니다.
사용 예
다음은 네트워크 서비스에서 서비스 요청 스레드의 스레드 풀입니다. 사전 구성된 Executors.newFixedThreadPool(int)
공장 방법을 사용합니다 .
class NetworkService implements Runnable {
private final ServerSocket serverSocket;
private final ExecutorService pool;
public NetworkService(int port, int poolSize)
throws IOException {
serverSocket = new ServerSocket(port);
pool = Executors.newFixedThreadPool(poolSize);
}
public void run() { // run the service
try {
for (;;) {
pool.execute(new Handler(serverSocket.accept()));
}
} catch (IOException ex) {
pool.shutdown();
}
}
}
class Handler implements Runnable {
private final Socket socket;
Handler(Socket socket) { this.socket = socket; }
public void run() {
// read and service request on socket
}
}
다음 메서드는 수신 거부 작업 ExecutorService
을 호출하여 두 단계 로 닫은 다음 필요한 경우 shutdown
를 호출 shutdownNow
하여 느린 작업을 취소합니다.
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
메모리 일관성 효과 : 어떤 작업이 하나 Runnable
또는 Callable
작업이 제출 ExecutorService
되기 전에 작업 스레드를 수행 하기 전에 발생하므로 결과가 통과 Future.get()
됩니다.
2. 집행 인
public class Executors
extends Object
를 들어 Executor
, ExecutorService
, ScheduledExecutorService
, ThreadFactory
식물과 실천 방법, 그리고 Callable
클래스는 패키지에 정의되어 있습니다. 이 범주는 다음 방법을 지원합니다.
- 이 메서드는
ExecutorService
일반적으로 사용되는 구성 설정을 만들고 반환 합니다. - 이 메서드는
ScheduledExecutorService
일반적으로 사용되는 구성 설정을 만들고 반환 합니다. - 이 메서드는 리팩토링의 특정 구현 방법이 아닌 "래퍼"서비스를 만들고 반환합니다.
- 이 메서드는 새로 만든 스레드
ThreadFactory
집합을 만들고 알려진 상태로 반환합니다 . - 이 메서드
Callable
는 메서드를 실행하는 데 사용할 수 있는 닫힌 양식을 만들고 반환합니다Callable
.
3. 코드
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestPool {
public static void main(String[] args) {
//1.创建服务
ExecutorService service = Executors.newFixedThreadPool(10);
//2.执行服务
service.execute(new Pools());
service.execute(new Pools());
service.execute(new Pools());
service.execute(new Pools());
service.execute(new Pools());
service.execute(new Pools());
service.execute(new Pools());
service.execute(new Pools());
service.execute(new Pools());
service.execute(new Pools());
// service.execute(new Pools());多于数目并不会创建,也不会报错
// service.execute(new Pools());
// service.execute(new Pools());
//3.结束服务
service.shutdown();
}
}
class Pools implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}