线程如何在完成工作后返回值?

编程入门 行业动态 更新时间:2024-10-03 23:31:21
本文介绍了线程如何在完成工作后返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我们有这个简单的例子:

Let's say we have this simple example:

public Example extends Thread{ String temp; public Example(){ } @Override public void run(){ . . . . temp = "a_value"; } public static void main(String[] args) { Example th = new Example(); th.start(); } }

线程如何完成job返回String temp?

How can the Thread after finishing its job return me the String temp?

推荐答案

利用(相对)新的 Callable< T> 而不是Runnable(1.5及更新版本):

Make use of the (relatively) new Callable<T> instead of Runnable (available in 1.5 and newer versions):

这是一个(简单)示例:

Here is a (simple) example:

import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Main { public static void main(final String[] argv) { final ExecutorService service; final Future<String> task; service = Executors.newFixedThreadPool(1); task = service.submit(new Foo()); try { final String str; // waits the 10 seconds for the Callable.call to finish. str = task.get(); // this raises ExecutionException if thread dies System.out.println(str); } catch(final InterruptedException ex) { ex.printStackTrace(); } catch(final ExecutionException ex) { ex.printStackTrace(); } service.shutdownNow(); } } class Foo implements Callable<String> { public String call() { try { // sleep for 10 seconds Thread.sleep(10 * 1000); } catch(final InterruptedException ex) { ex.printStackTrace(); } return ("Hello, World!"); } }

更多推荐

线程如何在完成工作后返回值?

本文发布于:2023-11-26 23:19:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635619.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   返回值   如何在   工作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!