多线程有返回值Callable的使用

本文介绍了一个用于推送短信状态报告的Java实现方案,包括线程池的配置与使用、异常处理策略以及通过HTTP POST请求发送状态报告的具体流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//调用方式
Callable<String> clazz = new PushReport(infos.toString(),account);
		 		NewThreadUtil.pushMessage(clazz);

 

package com.aaa.sms.util;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 
* @ClassName: NewThreadUtil 
* @date 2018年3月9日 下午2:16:47 
*
 */
public class NewThreadUtil{
//	Callable<T> clazz;
//	public NewThreadUtil(Callable<T> clazz){
//		this.clazz=clazz;
//	}
//	 Class<T> clazz;  
//
//	    public NewThreadUtil(Class<T> clazz) {  
//	        this.clazz = clazz;  
//	    }
	private static final Logger log=LoggerFactory.getLogger(NewThreadUtil.class);
	private static Integer corePoolSize = 5;
	private static Integer maximumPoolSize = 10;
	private static Long keepAliveTime = 10000L;//10分钟
	private static Integer queueCapacity = 25;//队列最大等待数
	private static  ExecutorService executorService = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
			java.util.concurrent.TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(queueCapacity));
	public  static void pushMessage(Callable<String> clazz){
		log.info("推送上行短信:主线程线程名称NewThreadUtil" + Thread.currentThread().getName());
		//Future<String> future 不能写返回值 否则会变成同步
		//多线程情况下,主线程try catch捕获不到子线程的throws exception
		try {
			executorService.submit(clazz);
		} catch (Exception e) {
			log.info("父类处理异常");
			e.printStackTrace();
		}
		
	}
	
	public static void shutDown(){
	 log.info("销毁线程池策略:服务停止停止接收消息");
		executorService.shutdownNow();
	}


	// 正常情况下主方法用try catch能够获取到子方法出现的异常
	 public static void function() throws NumberFormatException{
	 String s = "abc";
	 System.out.println(Double.parseDouble(s));
	 }
	
	 public static void main(String[] args) throws Exception{
	 try {
	 function();
	 } catch (NumberFormatException e) {
	 System.err.println("非数据类型不能转换。");
	 //e.printStackTrace();
	 }
	 }

}

 

package com.aaa.sms.task;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Callable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.anxinjie.AnXinJieUtil;
import com.credithc.sms.dto.SmsAccountDTO;
import com.credithc.sms.listeners.InitDatasListener;
import com.credithc.sms.service.ISmsAccountService;
import com.credithc.sms.util.ToolSpring;
/**
 * 
* @ClassName: PushReport 
* @date 2018年3月15日 下午5:57:45 
*
 */
public class PushReport implements Callable<String> {
	private static final Logger log=LoggerFactory.getLogger(PushReport.class);
	private String report;
	private String accoutId;
	public PushReport(String report,String accoutId){
		this.report=report;
		this.accoutId=accoutId;
	}
	public PushReport(){
	}
	@Override
	public String call() throws Exception {
		log.info("推送状态:线程名称"+Thread.currentThread().getName());
		ISmsAccountService ismsAccountService=(ISmsAccountService) ToolSpring.getBean("ismsAccountService");
		String url = null;
		SmsAccountDTO smsAccount = new SmsAccountDTO();
		smsAccount.setSmsAccountId(accoutId);
		try {
			SmsAccountDTO accounts = ismsAccountService.qrySmsAccountById(smsAccount);
				if ("1".equals(accounts.getIsPush())) {
					url = InitDatasListener.getPropertie(accounts.getSmsMappingSystem() + "_pushReport_url");
					System.out.println(accoutId+"获取状态请求地址"+url);
					System.out.println(accoutId+"获取状态报告请求内容"+"message="+report);
					String result=AnXinJieUtil.postURL("message="+report, url);
					System.out.println(accoutId+"获取状态返回结果"+result);
					

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "ok";
	}

	
	

}

 

### Java多线程中带有返回值的实现方式 在Java多线程编程中,`Callable` 和 `Future` 是实现带返回值任务的核心接口和类。以下详细介绍其实现方式。 #### Callable 接口 `Callable` 是一个类似于 `Runnable` 的接口,但它支持返回结果并可能抛出异常。`Callable` 的核心方法是 `call()`,它允许返回一个泛型类型的结果[^1]。 #### Future 接口 `Future` 表示异步计算的结果。通过 `Future`,可以检查计算是否完成、等待计算完成以及获取计算结果。`Future` 提供了如下的主要方法: - `boolean isDone()`:判断任务是否完成。 - `V get()`:获取任务的结果,如果任务未完成,则会阻塞当前线程直到任务完成。 - `V get(long timeout, TimeUnit unit)`:尝试在指定时间内获取结果,若超时则抛出异常。 #### 使用示例 以下是一个使用 `Callable` 和 `Future` 的完整示例,展示了如何在多线程环境中实现带返回值的任务。 ```java import java.util.concurrent.*; public class CallableFutureExample { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newFixedThreadPool(2); Callable<String> myCallable = () -> { Thread.sleep(5000); System.out.println("Task 1 executed at " + getStringDate()); return "Result from Task 1"; }; Callable<String> myCallable2 = () -> { Thread.sleep(3000); System.out.println("Task 2 executed at " + getStringDate()); return "Result from Task 2"; }; System.out.println("Submitting tasks at " + getStringDate()); Future<String> future = executor.submit(myCallable); Future<String> future2 = executor.submit(myCallable2); System.out.println("Tasks submitted at " + getStringDate()); System.out.println("Attempting to retrieve result from Task 1 at " + getStringDate()); System.out.println("Result from Task 1: " + future.get()); // 阻塞直到任务完成 System.out.println("Retrieved result from Task 1 at " + getStringDate()); System.out.println("Attempting to retrieve result from Task 2 at " + getStringDate()); System.out.println("Result from Task 2: " + future2.get()); // 阻塞直到任务完成 System.out.println("Retrieved result from Task 2 at " + getStringDate()); executor.shutdown(); } private static String getStringDate() { return new java.text.SimpleDateFormat("HH:mm:ss").format(new java.util.Date()); } } ``` #### 关键点解析 1. **提交任务**:通过 `ExecutorService` 的 `submit` 方法提交 `Callable` 任务,并返回一个 `Future` 对象。 2. **获取结果**:调用 `Future` 的 `get` 方法获取任务执行结果。如果任务尚未完成,`get` 方法将阻塞当前线程,直到任务完成[^1]。 3. **时间戳打印**:通过自定义的时间戳函数,展示任务的执行顺序和时间间隔。 #### 注意事项 - 如果任务执行过程中抛出了异常,`Future.get()` 将抛出 `ExecutionException`,其原因可以通过 `getCause()` 方法获取。 - 在高并发场景下,合理设置线程池大小以避免资源耗尽[^2]。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值