多线程主线程接受返回结果
来源:互联网 发布:淘宝版本过低怎么升级 编辑:程序博客网 时间:2024/05/21 10:26
当多线程需要接受子线程执行结果,根据执行结果触发不同的动作时,原来的extend Thread或者是implement Runable已经不能满足,JDK并发包部分为我们提供了线程池,使用线程池可以返回子线程执行结果
demo代码如下:
public class ThreadPoolTest implements Callable<String> {public static void main(String[] args) {ThreadPoolTest client = new ThreadPoolTest();client.fun();}@Overridepublic String call() throws Exception {System.out.println("执行此段代码");return "返回数据";}public void fun(){ExecutorService executor = Executors.newFixedThreadPool(3);Future<String> future = null;//int processor = Runtime.getRuntime().availableProcessors(); System.out.println("JVM可用处理器数:" + processor);for(int i = 0 ; i < 4; i++){future = executor.submit(new ThreadPoolTest());//If you would like to immediately block waiting for a task, //you can use constructions of the form result = exec.submit(aCallable).get(); //如果你想立刻阻塞等待任务,你可以这样使用:exec.submit(aCallable).get();try{System.out.println("返回结果是:" + future.get()); } catch (Exception e){e.printStackTrace();executor.shutdown();}}executor.shutdown(); }}构建线程池参数说明:
corePoolSize:线程池中至少存活的线程数,即使存活的线程是空闲的
maximumPoolSize:线程池中允许存活的最大线程数
keepAliveTime:当线程池中存在空闲线程时,空闲线程存活时间(超过这个时间就要回收掉)
unit:keepAliveTime单位
workQueue:存放任务的队列
threadFactory:executor创建线程的工厂
handler:执行阻塞时的handler(默认使用AbortPolicy)
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {}
- 多线程主线程接受返回结果
- java 多线程 主线程等待 子线程序列、并发结果
- 主线程循环接受命令
- NSOperationQueue返回主线程
- android js java 互调 子线程 主线程 直接调用 callback 返回结果
- C# 多线程编程,传参,接受返回值
- C# 多线程编程,传参,接受返回值
- C# 多线程编程,传参,接受返回值
- 多线程信号返回测试结果
- java多线程返回函数结果
- java多线程返回函数结果
- java多线程返回函数结果
- 多线程 : 使用 CompletionService 多线程返回结果
- 多线程之杀死主线程。。
- 多线程开发(主线程)
- Win32多线程之主线程
- WebRequest,WebResponse发送请求并接受返回结果
- MFC怎样发送http请求并接受返回的结果?
- Java 7之基础 - 强引用、弱引用、软引用、虚引用
- The method setCharacterEncoding(String) is undefined for the type HttpServletResponse
- [递归&&bfs]PAT1020 Tree Traversals
- Android图像处理之Bitmap类
- Request.QueryString["**"]发生“未将对象引用设置到对象的实例。”的解决方法
- 多线程主线程接受返回结果
- 腾讯京东合作
- poj1477
- 黑马程序员:初识socket编程(一)
- Qt编写activex所遇到的问题
- 使用Markdown写文档
- Yt初试锋芒--题与分析
- 理解接口开发中的*Ptr
- 方法节点的使用