Javaでスレッドプールを利用するシンプルサンプル
Javaコード:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPool {
public static void main(String[] args) {
//ExecutorService ThreadPool = Executors.newFixedThreadPool(3);
//ExecutorService ThreadPool = Executors.newCachedThreadPool();
ExecutorService ThreadPool = Executors.newSingleThreadExecutor();
for(int i=0;i<=5;i++){
final int task = i;
ThreadPool.execute(new Runnable() {
@Override
public void run() {
for(int j=0;j<=10;j++){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " ループ " + j + " タスク " + task);
}
}
});
}
//ThreadPool.shutdownNow();
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println(“停止");
}
}, 5, 2, TimeUnit.SECONDS);
}
}