0
0

More than 1 year has passed since last update.

ExecutorService Runnable/Callable

Posted at

Runnable:no return
Callable:return
Future interface#get methodでreturnを取得する

public class Outer {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService e = Executors.newSingleThreadExecutor();
        Runnable r = () -> {
            System.out.println("runnable");
        };
        Callable<Integer> c = () -> {
            return 1;
        };
        Future f = e.submit(r);
        try {
            System.out.println(f.get());
        } catch (ExecutionException ex) {
            Logger.getLogger(Outer.class.getName()).log(Level.SEVERE, null, ex);
        }
        Future<Integer> f2 = e.submit(r,0);
        try {
            System.out.println(f2.get());
        } catch (ExecutionException ex) {
            Logger.getLogger(Outer.class.getName()).log(Level.SEVERE, null, ex);
        }
        f2 = e.submit(c);
        try {
            System.out.println(f2.get());
        } catch (ExecutionException ex) {
            Logger.getLogger(Outer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
runnable
null
runnable
0
1
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0