欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

callback,future使用 CallbackFuture 

程序员文章站 2022-05-28 12:50:04
...
import java.util.concurrent.*;

public class FutureTaskTest {

    public static void main(String[] args) {

        // 线程1
        Callable<String> tempCall1 = new Callable<String>(){
            @Override
            public String call() throws Exception {
                Thread.sleep(5000);
                String back = "success";
                System.out.println("线程1执行了");
                return back;
            }
        };
        // 线程2
        Callable<String> tempCall2 = new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(5000);
                System.out.println("线程2执行了");
                return "fail";
            }
        };

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Future<String> future1 = executorService.submit(tempCall1);
        System.out.println("线程的状态是否取消:"+future1.isCancelled());
        String result1 = "";
        try {
            result1 = future1.get(4000, TimeUnit.MILLISECONDS);
        }catch (TimeoutException e) {
            System.out.println("线程1超时");
            future1.cancel(true);
        } catch (InterruptedException e) {
            System.out.println("线程1执行超时");
            e.printStackTrace();
        }catch(Exception e) {
            System.out.println("线程1执行异常");
            e.printStackTrace();
        }

        System.out.println("线程1返回的结果:"+result1);

        Future<String> future2 = executorService.submit(tempCall2);
        String result2 = "";
        try {
            result2 = future2.get(6000,TimeUnit.MILLISECONDS);
        }catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("线程2返回的结果:"+result2);

        executorService.shutdown();
    }
}

 

相关标签: Callback Future