在Java 线程中返回值的用法

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

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

代码如:

package com.threads.test;

import java.util.concurrent.Callable;

public class CallableThread implements Callable<String> {
private String str;
private int count=10;
public CallableThread(String str){
this.str=str;
}
//需要实现Callable的Call方法
public String call() throws Exception {
for(int i=0;i<this.count;i++){
System.out.println(this.str+" "+i);
}
return this.str;
}
}


在call方法中执行在run()方法中一样的任务,不同的是call()有返回值。
call的返回类型应该和Callable<T>的泛型类型一致。
测试代码如下:

package com.threads.test;

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

public class CallableTest {
public static void main(String[] args) {
ExecutorService exs=Executors.newCachedThreadPool();
ArrayList<Future<String>> al=new ArrayList<Future<String>>();
for(int i=0;i<10;i++){
al.add(exs.submit(new CallableThread("String "+i)));
}

for(Future<String> fs:al){
try {
System.out.println(fs.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}

}


submit()方法返回一个Futrue对象,可以通过调用该对象的get方法取得返回值。
通过该方法就能很好的处理线程中返回值的问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值