JAVA多线程笔试题
2018-08-26 17:18:33来源:博客园 阅读 ()
一、题目内容

二、我的答案
利用了线程池、考虑了超时处理、不知道这样写是否还有其他问题,或者更好更优的解决方案?
import java.util.*;
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
List<String> allPaymentList=Arrays.asList("余额","红包","余额宝","银行卡");
long start=System.nanoTime();
List<String> list=filterDisablePayment(allPaymentList);
double seconds=(System.nanoTime()-start)/1000000000.0;
System.out.println("总共耗时:"+seconds+"s");
for(String paymentType:list){
System.out.println(paymentType);
}
}
public static List<String> filterDisablePayment(List<String> allPaymentList){
List<String> results=new ArrayList<>();
ExecutorService executorService= Executors.newFixedThreadPool(allPaymentList.size());
List<Future<String>> futures=new ArrayList<>();
for(String paymentType:allPaymentList) {
futures.add(executorService.submit(new PaymentMethodCallable(paymentType)));
}
executorService.shutdown();
for(Future<String> future:futures){
try {
//超时处理机制
String result= future.get(4,TimeUnit.SECONDS);
if(result!=null){
results.add(result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return results;
}
public static Boolean PaymentIsEnabled(String paymentType) {
try {
//模拟远程服务调用所用时间
Thread.sleep(3000);
Random random=new Random();
boolean result=random.nextBoolean();
System.out.println("获取到结果:"+paymentType+":"+result);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
static class PaymentMethodCallable implements Callable<String> {
private String paymentType;
public String getPaymentType() {
return paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public PaymentMethodCallable(String paymentType) {
this.paymentType = paymentType;
}
@Override
public String call() {
if(PaymentIsEnabled(paymentType)) return paymentType;
return null;
}
}
}
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
下一篇:自动拆装箱
- 国外程序员整理的Java资源大全(全部是干货) 2020-06-12
- 2020年深圳中国平安各部门Java中级面试真题合集(附答案) 2020-06-11
- 2020年java就业前景 2020-06-11
- 04.Java基础语法 2020-06-11
- Java--反射(框架设计的灵魂)案例 2020-06-11
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash
