多线程中Callable/Future的疑问

zhuyx808 2009-07-07 10:41:32
纯贴拒绝无意义灌水:顶、学习、JF……之类的垃圾回复
(JDK1.5+)在多线程中,我们要得到子线程的结果一般就使用callable接口,用future来获取子线程的返回值。那么在试验中发现如果用了callable接口,那子线程中的操作好像都变成了“串行”?这是怎么回事?如果变成了串行,那我多线程还有什么意义??有没有高手来解答一下?

具体举个事例如下:10个人百米赛跑,裁判开枪10个人同时起跑,最后一个人跑完100米,比赛结束。那么在这个事例中,10个人就是10个子线程,每个线程干的事就是跑完100米。主线程要获取最后一个线程跑完100米的时间,然后主线程结束。

测试代码:

public abstract class FutureProxy{

private final class CallableImpl implements Callable{

public Object call() throws Exception {
return FutureProxy.this.createInstance();
}
}
private static class InvocationHandlerImpl implements InvocationHandler {

private Future future;

private volatile Object instance;

InvocationHandlerImpl(Future future){
this.future = future;
}

public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
synchronized(this){
if(this.future.isDone()){
this.instance = this.future.get();
}else{
while(!this.future.isDone()){
try{
this.instance = this.future.get();
}catch(InterruptedException e){
Thread.currentThread().interrupt();
}
}
}

return method.invoke(this.instance, args);
}
}
}

private static final class ThreadFactoryImpl implements ThreadFactory {

public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
}

private static ExecutorService service = Executors.newCachedThreadPool(new ThreadFactoryImpl());

protected abstract Object createInstance();

protected abstract Class getInterface();
public final Object getProxyInstance() {
Class interfaceClass = this.getInterface();
if (interfaceClass == null || !interfaceClass.isInterface()) {
throw new IllegalStateException();
}

Callable task = new CallableImpl();

Future future = FutureProxy.service.submit(task);

return (Object) Proxy.newProxyInstance(interfaceClass.getClassLoader(),
new Class[] { interfaceClass }, new InvocationHandlerImpl(future));
}
}


interface DateTest{

String getDate();
}

class DateTestImpl implements DateTest{

private String _date=null;

public DateTestImpl(){
try{
_date+=Calendar.getInstance().getTime();
}catch(Exception e){
}
}

public String getDate() {
//A.method是一个费时操作,比如读取数据库之类的……
A a=new A();
String s="";
if(a.method()){
s="a:"+Calendar.getInstance().getTime();
}else{
s="b:"+Calendar.getInstance().getTime();
}
return "date "+_date+":"+s;
}
}

class DateTestFactory extends FutureProxy{

protected Object createInstance() {
return new DateTestImpl();
}


protected Class getInterface() {
return DateTest.class;
}
}

public class Test{

public static void main(String[] args) {

DateTestFactory factory = new DateTestFactory();
DateTest[] dts = new DateTest[10];
for(int i=0;i<dts.length;i++){
dts[i]=(DateTest)factory.getProxyInstance();
}
for(int i=0;i<dts.length;i++){
System.out.println(dts[i].getDate());
}

}
}


在示例代码中运行发现,A.method是我想用多线程(循环顺序执行浪费时间为了节省时间使用多线程)执行的一个操作,可打出来的结果发现s值时间是顺序的:
Tue Jul 07 10:35:20 CST 2009
Tue Jul 07 10:35:25 CST 2009
Tue Jul 07 10:35:30 CST 2009

高手解答下为什么会这样?那我为了节省时间使用多线程该怎么办?
...全文
485 3 打赏 收藏 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
shagoo 2009-07-07
  • 打赏
  • 举报
回复
郁闷公司机器只有jre1.4没法测,找了一个例子,LZ测试看看有没有什么问题~

import java.util.*;
import java.util.concurrent.*;

public class CallableExample {

public static class WordLengthCallable
implements Callable {
private String word;
public WordLengthCallable(String word) {
this.word = word;
}
public Integer call() {
return Integer.valueOf(word.length());
}
}

public static void main(String args[]) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(3);
Set<Future<Integer>> set = new HashSet<Future≶Integer>>();
for (String word: args) {
Callable<Integer> callable = new WordLengthCallable(word);
Future<Integer> future = pool.submit(callable);
set.add(future);
}
int sum = 0;
for (Future<Integer> future : set) {
sum += future.get();
}
System.out.printf("The sum of lengths is %s%n", sum);
System.exit(sum);
}
}
zhuyx808 2009-07-07
  • 打赏
  • 举报
回复
THS
ThirstyCrow 2009-07-07
  • 打赏
  • 举报
回复
在你的程序中,DateTestImpl的getDate()方法都是在主线程中被调用的。子线程的工作只是创建DateTest实例。打印出的时间也不是子线程结束的时间。
代码下载链接: https://pan.quark.cn/s/a4b39357ea24 用户账户控制(UAC)白名单的配置 Windows7环境 UAC(User Account Control,用户帐户控制)是由微软在Windows Vista版本推出的一项旨在增强系统安全性的创新技术,该技术强制要求用户在执行可能干扰计算机正常运作的操作或进行更改会波及其他用户设置的变动前,必须提供相应的权限或管理员密码进行验证。通过对这些操作启动前进行授权确认,UAC能够有效阻止恶意软件及间谍软件在未获授权的状态下于计算机内进行安装或实施修改。 自从Vista版本问世以来,微软便开始推行这一全新的安全机制,可视为对系统安全防护的显著提升。尽管UAC确实能够在一定程度上对某些非法程序起到防御作用,但与此同时,这一功能也给众多用户带来了诸多不便。 因此,许多用户开始探寻是否存在类似于白名单的功能,以便将那些值得信赖的程序直接赋予运行权限。事实上,这类功能确实存在,不过微软并未将其作为标准配置提供。 网络上关于此问题的绝大多数建议都是建议禁用UAC,这种说法显然缺乏针对性,因为若用户希望禁用此功能,本就不会提出相关疑问。 通过运用微软官方发布的Microsoft Application Compatibility Toolkit 5.6版本,可以将信任的程序纳入系统白名单范畴。 获取Application Compatibility Toolkit 安装程序成功后会出现三个可执行文件 以管理员身份启动Compatibility Administrator 在Custom DataBases部分创建新的数据库,并添加一个Application Fix(在下方空白处点击右键,选择...
下载代码方式:https://pan.quark.cn/s/a4b39357ea24 DELL服务器的操作系统部署流程包含一系列细致的环节,其适用范围涵盖多种操作系统类型,例如Windows Server与Red Hat Linux等。在启动部署之前,必须确认服务器的光驱设备为DVD驱动器,并且需准备对应的系统安装媒介。下面将详细列出完整的部署步骤: 1. **启动准备**:将随服务器提供的Systems Management Tools and Documentation version 6.0光盘置入服务器光驱,随后设定服务器以光驱作为启动设备。此环节旨在确保服务器在启动阶段能够读取安装光盘内容。 2. **语言设定**:服务器启动后,选定简体文作为部署语言,并确认接受许可协议条款。 3. **时区选择**:在部署期间,需设定时区为北京、香港、重庆或乌鲁木齐,依据实际地理位置进行适配选择。 4. **系统类型选择**:随后,需选定计划部署的操作系统,支持的版本包括Server 2003 SP2、Server 2003 SP2 64位版本、Windows 2003 SBS SP2、Server 2008、Windows 2008 SBS/EBS x64版本等,以及多种Red Hat和SUSE Linux版本。 5. **RAID设定**:若服务器出厂时已预设RAID配置,则可选择跳过此步骤。若需重新设定RAID,操作时需格外小心,因为这一过程可能引发硬盘数据遗失。 6. **引导分区规划**:设定引导分区的大小,通常C盘建议预留至少20GB的空间,具体容量需根据系统需求进行调整。 7. **网络设定**:网络设定可在系统部署完成后执行,部署期间建议暂时拔除...

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧