java多线程返回函数结果

两种方式:一种继承Thread类实现;一种通过实现Callable接口。

第一种方法:

因为实现Thread类的run方法自身是没有返回值的,所以不能直接获得线程的执行结果,但是可以通过在run方法里把最后的结果传递给实例变量,然后通过getXX方法获取该实例变量的值。继承实现的代码:

[java]view plaincopy

    classRunThreadextendsThread{privateStringrunLog;privateBufferedReaderbr;{runLog="";}publicRunThread(BufferedReaderbr){this.br=br;}publicvoidrun(){try{Stringoutput="";while((output=br.readLine())!=null){this.runLog+=output+"\n";}}catch(IOExceptione){e.printStackTrace();}}publicStringgetRunLog(){returnthis.runLog;}}

第二种方法:

继承Callable接口后需要实现call方法,而call方法默认是可以有返回值的,所以可以直接返回想返回的内容。接口的实现代码:

[java]view plaincopy

    classCallThreadimplementsCallable<String>{privateStringrunLog;privateBufferedReaderbr;{runLog="";}publicCallThread(BufferedReaderbr){this.br=br;}@OverridepublicStringcall()throwsException{try{Stringoutput="";while((output=br.readLine())!=null){runLog+=output+"\n";}}catch(IOExceptione){returnrunLog;}returnrunLog;}}

下面就来调用了。

第一种方式的调用代码:

[java]view plaincopy

    RunThreadth1=newRunThread(standout);th1.start();RunThreadth2=newRunThread(standerr);th2.start();th2.join();//保障前面2个线程在主进程之前结束,否则获取的结果可能为空或不完整runLog+=th1.getRunLog()+"\n";runLog+=th2.getRunLog()+"\n";

第二种方式的调用代码:[java]view plaincopy

    ExecutorServiceexs=Executors.newCachedThreadPool();ArrayList<Future<String>>al=newArrayList<Future<String>>();al.add(exs.submit(newCallThread(standout)));al.add(exs.submit(newCallThread(standerr)));for(Future<String>fs:al){try{runLog+=fs.get()+"\n";}catch(InterruptedExceptione){e.printStackTrace();}catch(ExecutionExceptione){e.printStackTrace();}}

而消极的人则在每个机会都看到某种忧患。

java多线程返回函数结果

相关文章:

你感兴趣的文章:

标签云: