Callable †
- Java 5 から、別スレッドで実行した結果を返せるようになった
package sandbox;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main2 {
public static void main(String[] args) {
FutureTask<String> future = new FutureTask(new Callable<String>() {
@Override
public String call() throws Exception {
return Thread.currentThread().getName();
}
});
new Thread(future).start();
try {
System.out.println(future.get());
} catch (InterruptedException ex) {
Logger.getLogger(Main2.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(Main2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
- future.get() の引数にタイムアウトを設定できる
try {
System.out.println(future.get(2L, TimeUnit.SECONDS));
} catch (InterruptedException ex) {
Logger.getLogger(Main2.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(Main2.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimeoutException ex) {
Logger.getLogger(Main2.class.getName()).log(Level.SEVERE, null, ex);
}
タイムアウトが起きると TimeoutException? が発生する
- Runnable も返値なしの Callable として同じように扱える。
Thread Pool †
package sandbox;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
try {
ExecutorService thPool
= new ThreadPoolExecutor(
0, Integer.MAX_VALUE,
30L, TimeUnit.SECONDS,
new SynchronousQueue());
Future<String> future = thPool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
return Thread.currentThread().getName();
}
});
System.out.println("MAIN:" + Thread.currentThread().getName());
System.out.println("SUB :" + future.get());
thPool.shutdown();
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
- ThreadPoolExecutor? のコンストラクタのひな形が用意されている
- ExecutorService? Executors.newSingleThreadExecutor?()
- new ThreadPoolExecutor?(0, 1, 0L, TimeUnit?.SECONDS, new SynchronousQueue?());
- ExecutorService? Executors.newFixedThreadPool?(int nThreads)
- new ThreadPoolExecutor?(nThread, nThread, 0L, TimeUnit?.SECONDS, new SynchronousQueue?());
- ExecutorService? Executors.newCachedThreadPool?()
- new ThreadPoolExecutor?(0, Integer.MAX_VALUE, 60L, TimeUnit?.SECONDS, new SynchronousQueue?());
- thPool.shutdown() をして、プールしているスレッドを終わらせないとアプリが終わらない
Java#JavaSE