Callable


 

 

package test.com.hisi.d;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
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 DTest {

    public static void main(String[] args) {
        int timeout = 2;
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Boolean result = false;
        Future<Boolean> future = executor.submit(new TaskThread("发送请求"));//将任务提交给线程池
        try {
            System.out.println("begin:");
            result = future.get(timeout, TimeUnit.SECONDS);   //1
            //result = future.get(timeout, TimeUnit.MILLISECONDS); //2
            System.out.println("发送请求任务的返回结果: " + result);  
        } catch (InterruptedException e) {
            System.out.println("线程中断出错。");
            future.cancel(true);// 中断执行此任务的线程
        } catch (ExecutionException e) {
            System.out.println("线程服务出错。");
            future.cancel(true);
        } catch (TimeoutException e) {// 超时异常
            System.out.println("超时。");
            future.cancel(true);
        } finally {
            System.out.println("线程服务关闭。");
            executor.shutdown();
        }
    }

    static class TaskThread implements Callable<Boolean> {
        private String task;

        public TaskThread(String temp) {
            this.task = temp;
        }

        public Boolean call() {
            //for用于模拟超时
            for (int i = 0; i < 999999999; i++) {
                if (i == 999999998) {
                    System.out.println(task + " 成功!");
                }
                if (Thread.interrupted()) {
System.out.println("---interrupted----"); return false; } } System.out.println("继续执行.........."); return true; } } }

begin:
发送请求 成功!
继续执行..........
发送请求任务的返回结果: true
线程服务关闭。

--------------------------------------

若使用result = future.get(timeout, TimeUnit.MILLISECONDS);则结果为

begin:
超时。
---interrupted----
线程服务关闭。

package test.com.hisi.d;

import java.util.concurrent.Callable;

class MyCallable implements Callable<Object> {
    private int flag;

    public MyCallable(int flag) {
        this.flag = flag;
    }

    public String call() throws Exception {
        if (this.flag == 0) {
            return "flag = 0";
        }

        if (this.flag == 1) {
            try {
                while (true) {
                    System.out.println("looping.");
                    Thread.sleep(2000);
                }
            } catch (InterruptedException e) {
                System.out.println("Interrupted");
            }

            return "false";
        } else {
            throw new Exception("Bad flag value!");
        }
    }
}

 

package test.com.hisi.d;

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

public class FutureGetBlock {

    public static void main(String[] args) {
        // 定义3个Callable类型的任务
        MyCallable task1 = new MyCallable(0);
        MyCallable task2 = new MyCallable(1);
        MyCallable task3 = new MyCallable(2);
        // 创建一个执行任务的服务
        ExecutorService es = Executors.newFixedThreadPool(3);

        try {
            // 提交并执行任务,任务启动时返回了一个Future对象,
            // 如果想得到任务执行的结果或者是异常可对这个Future对象进行操作
            Future<?> future1 = es.submit(task1);
            // 获得第一个任务的结果,如果调用get方法,当前线程会等待任务执行完毕后才往下执行
            System.out.println("task1: " + future1.get());
            Future<?> future2 = es.submit(task2);
            // 等待5秒后,再停止第二个任务。因为第二个任务进行的是无限循环
            Thread.sleep(5000);
            System.out.println("task2 cancel: " + future2.cancel(true));
            // 获取第三个任务的输出,因为执行第三个任务会引起异常
            // 所以下面的语句将引起异常的抛出
            Future<?> future3 = es.submit(task3);
            System.out.println("task3: " + future3.get());
        } catch (Exception e) {
            System.out.println(e.toString());
        }

        // 停止任务执行服务
        es.shutdownNow();
    }
}

task1: flag = 0
looping.
looping.
looping.
Interrupted
task2 cancel: true
java.util.concurrent.ExecutionException: java.lang.Exception: Bad flag value!

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM