• 在Java 线程中返回值的用法


    http://icgemu.iteye.com/blog/467848

    有时在执行线程中需要在线程中返回一个值;常规中我们会用Runnable接口和Thread类设置一个变量;在run()中改变变量的值,再用一个get方法取得该值,但是run何时完成是未知的;我们需要一定的机制来保证。 

    在在Java se5有个Callable接口;我们可以用该接口来完成该功能; 

    代码如: 
    Java代码  收藏代码
    1. package com.threads.test;  
    2.   
    3. import java.util.concurrent.Callable;  
    4.   
    5. public class CallableThread implements Callable<String> {  
    6.     private String str;  
    7.     private int count=10;  
    8.     public CallableThread(String str){  
    9.         this.str=str;  
    10.     }  
    11.     //需要实现Callable的Call方法  
    12.     public String call() throws Exception {  
    13.         for(int i=0;i<this.count;i++){  
    14.             System.out.println(this.str+" "+i);  
    15.         }  
    16.         return this.str;  
    17.     }  
    18. }  


    在call方法中执行在run()方法中一样的任务,不同的是call()有返回值。 
    call的返回类型应该和Callable<T>的泛型类型一致。 
    测试代码如下: 
    Java代码  收藏代码
    1. package com.threads.test;  
    2.   
    3. import java.util.ArrayList;  
    4. import java.util.concurrent.ExecutionException;  
    5. import java.util.concurrent.ExecutorService;  
    6. import java.util.concurrent.Executors;  
    7. import java.util.concurrent.Future;  
    8.   
    9. public class CallableTest {   
    10.     public static void main(String[] args) {  
    11.         ExecutorService exs=Executors.newCachedThreadPool();  
    12.         ArrayList<Future<String>> al=new ArrayList<Future<String>>();  
    13.         for(int i=0;i<10;i++){  
    14.             al.add(exs.submit(new CallableThread("String "+i)));  
    15.         }  
    16.           
    17.         for(Future<String> fs:al){  
    18.             try {  
    19.                 System.out.println(fs.get());  
    20.             } catch (InterruptedException e) {  
    21.                 e.printStackTrace();  
    22.             } catch (ExecutionException e) {  
    23.                 e.printStackTrace();  
    24.             }  
    25.         }  
    26.     }  
    27.   
    28. }  

    submit()方法返回一个Futrue对象,可以通过调用该对象的get方法取得返回值。 
    通过该方法就能很好的处理线程中返回值的问题。
  • 相关阅读:
    PHP 获取请求里的 header字段以及发送header
    宝塔链接数据库
    链表中头结点和头指针
    git How to resolve a Git “CONFLICT (modify/delete)”?
    yii 执行mysql:既要添加数据又要更新数据
    recv() failed (104: Connection reset by peer) while reading response header from upstream
    Linux磁盘空间满了,定位到mysql日志,删除
    mysql 字符乱码
    php message queue
    CGI 、fastcgi、php-cgi、php-fpm
  • 原文地址:https://www.cnblogs.com/donaldlee2008/p/5290172.html
Copyright © 2020-2023  润新知