`
落叶换新叶
  • 浏览: 11179 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

callback,future使用

阅读更多
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();
    }
}

?

1
0
分享到:
评论
Global site tag (gtag.js) - Google Analytics 重庆时时彩怎么作弊的