概述
多线程中需要返回值, java中有个fork/join模型, 没有细研究, 简单实用callable进行了返回
Thread1
package com.iwhere.easy.travel.test.thread; import java.util.concurrent.Callable; import org.springframework.web.client.RestTemplate; import com.alibaba.fastjson.JSONObject; public class Thread1 implements Callable<String>{ @Override public String call() throws Exception { Thread.sleep(5000); System.out.println("thread1 sleep 5s"); new RestTemplate().getForObject("http://abc.2314", JSONObject.class); return "i am thread one"; } }
Thread2
package com.iwhere.easy.travel.test.thread; import java.util.concurrent.Callable; public class Thread2 implements Callable<String>{ @Override public String call() throws Exception { Thread.sleep(2000); System.out.println("thread2 sleep 2s"); if (1 == 1) throw new RuntimeException(); return "i am thread two"; } }
Thread3
package com.iwhere.easy.travel.test.thread; import java.util.concurrent.Callable; public class Thread3 implements Callable<String>{ @Override public String call() throws Exception { Thread.sleep(8000); System.out.println("thread3 sleep 8s"); // Thread.currentThread().interrupt(); return "i am thread three"; } }
main类
package com.iwhere.easy.travel.test.thread; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class MyThreadTest { private static ExecutorService threadPool = Executors.newFixedThreadPool(20); public static void main(String[] args) throws InterruptedException, ExecutionException { Thread1 thread1 = new Thread1(); Future<String> futureTask1 = threadPool.submit(thread1); Thread2 thread2 = new Thread2(); Future<String> futureTask2 = threadPool.submit(thread2); Thread3 thread3 = new Thread3(); Future<String> futureTask3 = threadPool.submit(thread3); String string1 = null; String string2 = null; String string3 = null; try { string1 = futureTask1.get(); }catch (Exception e) { futureTask1.cancel(true); } try { string2 = futureTask2.get(); }catch (Exception e) { futureTask2.cancel(true); } try { string3 = futureTask3.get(); }catch (Exception e) { futureTask3.cancel(true); } // Thread.currentThread().wait(1000); // futureTask1.cancel(true); // futureTask2.cancel(true); // futureTask3.cancel(true); System.out.println(string1 + ": " + string2 + ": " + string3); threadPool.shutdown(); } }
这样在线程中抛出异常,仍然可以,
有一个问题仍然存在, 要是线程中莫名停止了, 就不会反回值 了..
转载于:https://www.cnblogs.com/wenbronk/p/7221081.html
最后
以上就是还单身龙猫为你收集整理的java-多线程future等待返回的全部内容,希望文章能够帮你解决java-多线程future等待返回所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复