スレッドプール
事前に複数のスレッドを作成し、事前にスレッドプールに入れ、使用時に直接取得し、使用後にプールに戻します。頻繁な作成と破壊を回避し、再利用を実現できます。
メリット
- 応答速度を向上させる
- リソース消費を削減します
- スレッド管理を容易にする
- corePoolSize:コアプールのサイズ
- maximunPoolSize:スレッドの最大数
- keepAliveTime:アライブタイムを維持
1.ExecutorService
public interface ExecutorService
extends Executor
Executor
管理端末及び方法が進歩発生一つ以上の非同期タスクを追跡するために使用することができるFuture
方法を提供します。
1つExecutorService
を閉じることができます。これにより、新しいタスクが拒否されます。を閉じるにExecutorService
は、2つの異なる方法が用意されています。このメソッドを使用すると、shutdown()
以前に送信されたタスクを実行前に終了できますが、このメソッドはshutdownNow()
、タスクが現在実行中のタスクを停止しようとするのを待つことを防ぎます。終了時に、エグゼキュータにはアクティブなタスク、実行を待機しているタスク、および送信する新しいタスクがありません。未使用のものExecutorService
は、リソースを回復できるように閉じる必要があります。
メソッドsubmit
拡張メソッドベースExecutor.execute(Runnable)
は、Future
実行をキャンセルしたり、完了を待つことができるメソッドを作成して返します。メソッドinvokeAny
とinvokeAll
実行本体の実行の最も一般的な形式、実行されたタスクのコレクション、そしてそれらの少なくとも1つまたはすべてが完了するのを待ちます。(クラス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
を呼び出して2段階で終了し、必要に応じて、残っているタスクをキャンセルする次の方法: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();
}
}
メモリ整合性効果:1つ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());
}
}