最初にJavaスレッドプールを試してください

スレッドプール

事前に複数のスレッドを作成し、事前にスレッドプールに入れ、使用時に直接取得し、使用後にプールに戻します。頻繁な作成と破壊を回避し、再利用を実現できます。

メリット

  • 応答速度を向上させる
  • リソース消費を削減します
  • スレッド管理を容易にする
    • corePoolSize:コアプールのサイズ
    • maximunPoolSize:スレッドの最大数
    • keepAliveTime:アライブタイムを維持

1.ExecutorService

public interface ExecutorService
extends Executor

Executor管理端末及び方法が進歩発生一つ以上の非同期タスクを追跡するために使用することができるFuture方法を提供します。

1つExecutorServiceを閉じることができます。これにより、新しいタスクが拒否されます。を閉じるにExecutorServiceは、2つの異なる方法が用意されています。このメソッドを使用すると、shutdown()以前に送信されたタスクを実行前に終了できますが、このメソッドはshutdownNow()、タスクが現在実行中のタスクを停止しようとするのを待つことを防ぎます。終了時に、エグゼキュータにはアクティブなタスク、実行を待機しているタスク、および送信する新しいタスクがありません。未使用のものExecutorServiceは、リソースを回復できるように閉じる必要があります。

メソッドsubmit拡張メソッドベースExecutor.execute(Runnable)は、Future実行をキャンセルしたり、完了を待つことができるメソッドを作成して返しますメソッドinvokeAnyinvokeAll実行本体の実行の最も一般的な形式、実行されたタスクのコレクション、そしてそれらの少なくとも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段階で終了、必要に応じて、残っているタスクをキャンセルする次の方法shutdownshutdownNow

 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

以下のためにExecutorExecutorServiceScheduledExecutorServiceThreadFactory植物や実用的な方法、および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());
    }
}

おすすめ

転載: blog.csdn.net/joey_ro/article/details/109963581