线程结果回调Runnable、Callable、Future、FutureTask

//线程可以用我们常用的Runnable接口实现,但是这样没有返回值,如果想要线程运行结果,可以使用Callable、Future、FutureTask使用

Runnable

        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) { executorService.submit(new RunTask()); }
        if (!executorService.isShutdown()) { executorService.shutdown(); }
    //一般线程
    public class RunTask implements Runnable {
        @Override
        public void run() {
            Log.v("-->run", Thread.currentThread().getName() + "execute!!!");
        }
    }

线程结果回调Runnable、Callable、Future、FutureTask_第1张图片

Callable、Future

        try {
            List<Future<String>> results = new ArrayList<>();
            ExecutorService executorService = Executors.newCachedThreadPool();
            for (int i = 0; i < 7; i++) {
                results.add(executorService.submit(new CallTask()));
            }
            for (Future<String> future : results) {
                Log.v("-->future", future.get());
            }
            Log.v("-->", "Main complete");

            if (!executorService.isShutdown()) {
                executorService.shutdown();
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    //回调线程
    public class CallTask implements Callable<String> {
        @Override
        public String call() throws Exception {
            Log.v("-->call", Thread.currentThread().getName() + "execute!!!");
            return Thread.currentThread().getName() + "complete";
        }
    }

FutureTask

        try {
            ExecutorService executorService = Executors.newCachedThreadPool();
            FutureTask<String> futureTask = new FutureTask<>(
                    new Callable<String>() {
                        @Override
                        public String call() throws Exception {
                            Log.v("-->call", Thread.currentThread().getName() + "execute!!!");
                            return Thread.currentThread().getName() + "complete";
                        }
                    });
            // 提交futureTask
            executorService.submit(futureTask);
            Log.v("-->futureTask", futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

这里写图片描述

你可能感兴趣的:(线程)