线程Callable写法

简单的例子

package com.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CallableTest {

    static class DeliverCallable implements Callable{
        //执行方法,相当于 Runnable 的 run, 不过可以有返回值和抛出异常
        @Override
        public String call() throws Exception {
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getName()+":您的外卖已送达");
            return Thread.currentThread().getName()+"送达时间:"+System.currentTimeMillis()+"\n";
        }
    }

    public static void main(String[] args) {

        List> futureTasks = new ArrayList<>(2);

        for (int i = 0; i < 4; i++) {
            DeliverCallable callable = new DeliverCallable();
            FutureTask futureTask = new FutureTask<>(callable);
            futureTasks.add(futureTask);
            Thread thread = new Thread(futureTask, "送餐员" + i);
            thread.start();
        }

        //线程非安全的
        StringBuilder results = new StringBuilder();
        for (int i = 0; i < futureTasks.size(); i++) {
            try {
                //获取线程返回结果,没返回就会阻塞
                results.append(futureTasks.get(i).get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        System.out.println(System.currentTimeMillis() + " 得到结果:\n" + results);

    }

}

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