スレッドプールのアイデアの概要
- スレッドを作成して頻繁に除去して、効率を向上させることができ、同じスレッドの時間、繰り返し使用することを要します
2.スレッドプールの概念
- スレッドプール:スレッドのコレクション
LinkedList<Thread> threads = new LinkedList<>();
スレッドを追加します:
LinkedList<Thread> threads = new LinkedList<>();
threads.add(new Thread("线程1"));
threads.add(new Thread("线程2"));
threads.add(new Thread("线程3"));
threads.add(new Thread("线程4"));
呼び出し元のスレッド:
Thread thread01 = threads.removeFirst();
Thread thread02 = threads.removeFirst();
使用後、また戻っスレッド
threads.addLast(thread01);
threads.addLast(thread02);
JDK1.5後:
- スレッドプールファクトリクラスを使用
Executors
する静的メソッド内でnewFixedThreadPool()
スレッドプールの指定された数を生成します
ExecutorService es = Executors.newFixedThreadPool(3); 生产3个线程,
- 作成
Runnable
クラスを実装インタフェース、書き換えというrun()
スレッドタスクを設定する方法、
public class ImpRunnable implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
- 使用
ExecutorService
方法をsubmit()
、ネジ付きタスク(実装クラス)を渡して、オープンスレッド実行run()
方法
es.submit(new ImpRunnable());
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Demo05 {
public static void main(String[] args) {
ExecutorService es= Executors.newFixedThreadPool(3);
es.submit(new ImpRunnable());
es.submit(new ImpRunnable());
es.submit(new ImpRunnable());
es.submit(new ImpRunnable());
}
}
- 使用
ExecutorService
方法shutdown()
破壊スレッドプールを(推奨されません)
es.shutdown();