Java如何使用Callable获得线程返回值呢?

戚薇 Java经验 发布时间:2023-06-24 22:27:01 阅读数:10574 1
下文笔者讲述Callable获取线程返回值的方法分享

获取线程返回值的实现思路

1.通过Callable实现线程
2.使用future获取线程返回值
例:获取线程返回值的示例
package com.java265;
 
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;
import java.util.concurrent.FutureTask;

public class TestCallable {
 
	public static void main(String[] args) {
		//Callable,ExecutorService,Future
		ExecutorService executor = Executors.newCachedThreadPool();
		Future<String> future = executor.submit(new Callable<String>() {
			@Override
			public String call() throws Exception {
				Thread.sleep(1000);
				return "abc";
			}
		});
		System.out.println("1...");
		try {
			System.out.println(future.get());//阻塞等待返回
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
		//Callable,FutureTask,ExecutorService
		FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
			@Override
			public Integer call() throws Exception {
				return 12345;
			}
		});
		executor.submit(futureTask);
		System.out.println("2...");
		try {
			System.out.println(futureTask.get());
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
		//Callable,FutureTask,Thread
		FutureTask<Integer> futureTask2 = new FutureTask<Integer>(new Callable<Integer>() {
			@Override
			public Integer call() throws Exception {
				return 6789;
			}
		});
		new Thread(futureTask2).start();
		System.out.println("3...");
		try {
			System.out.println(futureTask2.get());
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	} 
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202306/16876168686884.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者