package com.xf;

import java.util.concurrent.Callable;

public class bbb implements Callable {
    private final String b1;

    public bbb(String b1) {
        this.b1 = b1;
    }

    @Override
    public Object call() throws Exception {
        System.out.println(b1);
        return null;
    }

}

 

package com.xf;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class aaa {

    public static void main(String[] args) {
//        Callable<String> task = new Callable<String>() {
//            @Override
//            public String call() throws Exception {
//                // 设置执行响应时间的方法体
//                // 执行时间需要10秒钟
//                Thread.sleep(10000);
//                return null;
//            }
//        };

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        try {
//            Future<String> future = executorService.submit(task);
            bbb b = new bbb("我是参数");
            Future<String> future = executorService.submit(b);
            String obj = future.get(1000 * 1, TimeUnit.MILLISECONDS); // 任务处理超时时间设为 1 秒
            System.out.println("任务成功返回:" + obj);
        } catch (TimeoutException ex) {
            System.out.println("处理超时啦....");
            ex.printStackTrace();
        } catch (Exception e) {
            System.out.println("处理失败.");
            e.printStackTrace();
        } finally {
            System.out.println("关闭线程池.");
            executorService.shutdown();
        }
    }

}