1. 程式人生 > >JAVA多線程筆試題

JAVA多線程筆試題

技術 答案 args disable this arraylist null mit tex

一、題目內容
技術分享圖片

二、我的答案

  利用了線程池、考慮了超時處理、不知道這樣寫是否還有其他問題,或者更好更優的解決方案?

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;
    }
}

}

JAVA多線程筆試題