目標(biāo):一個(gè)線程出現(xiàn)異常不應(yīng)該影響其他未執(zhí)行的線程的執(zhí)行,,并能把整個(gè)程序運(yùn)行完 代碼如下: import lombok.Data;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger;
@Data public class RefundAnalysis { String detailId = null; /**資金平臺(tái)處理過(guò),,返回結(jié)果也是成功的*/ AtomicInteger refundOkTotal = new AtomicInteger(0); /**是否需退款回調(diào)*/ AtomicBoolean isCallback = new AtomicBoolean(false); /**統(tǒng)計(jì)TdConstant.REFUND_RESULT.FAIL,資金平臺(tái)有處理過(guò),,但處理失敗*/ //int refundFailTotal = 0; AtomicInteger refundFailTotal = new AtomicInteger(0); }
public static void main(String[] args) { RefundAnalysis refundAnalysis = new RefundAnalysis(); Stream.of(1,2,3,4,5,6).parallel().forEach(i->{ /**要捕獲異常,,不往外拋出*/ try{ int j = i/(3-i); refundAnalysis.getRefundOkTotal().incrementAndGet(); System.out.println(i); }catch (Exception e){ log.error(e.getLocalizedMessage()); refundAnalysis.getRefundFailTotal().incrementAndGet(); } }); /**如果并行處理里的異常不捕獲的話,,則會(huì)拋出導(dǎo)致下面2行代碼不會(huì)執(zhí)行*/ System.out.println("oktotal="+refundAnalysis.getRefundOkTotal().intValue()); System.out.println("failtotal="+refundAnalysis.getRefundFailTotal().intValue()); }
|